SELECT * FROM tblPosts WHERE tblPosts.usersID = (SELECT tblFriends.friendsID WHERE tblFriends.myID = ‘$myID’) ORDER BY tblPosts.date DESC; [closed]

SELECT * FROM tblPosts WHERE tblPosts.usersID = (SELECT tblFriends.friendsID WHERE tblFriends.myID = '$myID') ORDER BY tblPosts.date DESC;

This doesn’t through an error but it also doesn’t work. I think I need a join statement maybe? There are several fields in tblPost. ID, Comment, Date, userID, etc… Using my $myID variable I want to output <<<while($row = $result->fetch_assoc())>>> all the matching rows from tblPosts WHERE tblPosts.usersID equals every friend in my tblFriends.friendsID column when tblFriends.myID = ‘$myID’ and then ORDER BY tblPosts.date DESC? Any help would be great! Thank you.

Sending Form Data using Ajax and PHP but it shows Undefined Index on the .php file

I’m a bit new to Ajax and HTTP requests and followed some guides to send and save data when I encountered this problem.

I tried sending an object form using ajax through PHP, it shows fine in the preview but when clicking on the actual PHP file it gives me undefined index errors.

On the HTML file preview

Preview on the HTML File

When clicked and redirected to the PHP file

PHP File Errors

JQUERY

jQuery(document).ready(function ($) {

    $('.tui-image-editor-download-btn').on('click', function (e) {

        var blob = dataURLtoBlob(imageEditor.toDataURL());
        console.log(blob);

        var formData = new FormData();
           formData.append('croppedImage', blob,"Image.png");
 
        $.ajax({
            contentType: false, 
            processData: false,
            url: 'upload.php',
            type: 'POST',
            data: formData,
            success: function (data) {
                alert(formData);
            },
            error: function(xhr, status, error) {
                alert('UPLOAD FAILED, PLEASE TRY AGAIN...');
            }
        });
        return false;
    });
});

PHP

<?php

  $files = $_FILES['croppedImage'];
 echo '<pre>'; print_r($files); echo '</pre>';
 
 $imageData = file_get_contents($_FILES['croppedImage']['tmp_name']); 
 echo sprintf('<img src="data:image/png;base64,%s" />', base64_encode($imageData));

?>

Function is not returning a value, but printing within the function? [duplicate]

Sure this is a oversight, My Function is to search directories looking for a filename.
Save to an array for use in another part of the program.

Function works fine, however the results never return outside of the function. I can print the results fine within the function, But this is no use as i need to use this later on. Is there any reason why this is happening?

<?php
function search_file($dir,$file_to_search){
    $files = scandir($dir);
    foreach($files as $key => $value){
        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
        if(!is_dir($path)) {
            if($file_to_search == $value){
                $resultfind[] = $path;
            }
        } else if($value != "." && $value != "..") {
            search_file($path, $file_to_search);
        }
    }
    print_r ($resultfind) ;
    return $resultfind ;
}


$file_to_search = "SessionLock.txt";
$searchResults = search_file('.',$file_to_search);

echo "The Returned Results are <br> " ;
print_r ($searchResults) ;

How can I resolve the Request exceeded the limit of 10 internal redirects issue?

my .htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On
    
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]
    
    # Send Requests To Front Controller...
    RewriteCond %{ENV:REDIRECT_STATUS} ^$
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

the Request exceeded the limit of 10 internal redirects 500 internal error

Google SAML APP SSO integrate with php application

I am using the php SAML library for SAML integration in php applucation(SP) with google as IDP.
I followed the step for the configuration of SAML toolkit for PHP in this link.

  • I add application SAML Test Connector (IdP w/ attr).
  • I add the content of repository Github to my hosting to run PHP code.
  • I defined the variable in demo1/settings.php

enter image description here

But I am getting the response from google suit (IDP)

enter image description here

Even I had tried he same code with Onelogin as IDP and it was working. Don’t know why it’s not working with Google as IDP.

Please Help! if anyone having an idea for the same.

Thanks in advance.

CakeHttpExceptionInvalidCsrfTokenException Missing or incorrect CSRF cookie type. in CakePHP

We’ve recently upgraded from an old version of CakePHP (3.10) to CakePHP (4.3).
Since then using the CSRF functionality causes the ‘[CakeHttpExceptionInvalidCsrfTokenException] Missing or incorrect CSRF cookie type.’ error.

In the Application.php part of the core we’ve added;

public function middleware($middlewareQueue): CakeHttpMiddlewareQueue
    {
        $middlewareQueue
            // Catch any exceptions in the lower layers,
            // and make an error page/response
            ->add(new ErrorHandlerMiddleware(Configure::read('Error')))

            // Handle plugin/theme assets like CakePHP normally does.
            ->add(new AssetMiddleware([
                'cacheTime' => Configure::read('Asset.cacheTime'),
            ]))

            // Add routing middleware.
            // Routes collection cache enabled by default, to disable route caching
            // pass null as cacheConfig, example: `new RoutingMiddleware($this)`
            // you might want to disable this cache in case your routing is extremely simple
            ->add(new RoutingMiddleware($this, '_cake_routes_'))
            
            // Parse various types of encoded request bodies so that they are
            // available as array through $request->getData()
            // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
            ->add(new BodyParserMiddleware())

            // Cross Site Request Forgery (CSRF) Protection Middleware
            // https://book.cakephp.org/4/en/security/csrf.html#cross-site-request-forgery-csrf-middleware
            ->add(new CsrfProtectionMiddleware([
                'httponly' => false,
            ]));

        return $middlewareQueue;
    }

I did some digging and cleaning the cookies works (Client sided) but most of the traffic we get are webhooks from different clients. Is there a way to reset the cookies so that these webhooks can come through without generating the error?

Why value is not updated in JSON using PHP and jQuery?

I stuck at the JSON file whereby the value is not updated.

Reference:

  1. How to update/edit a JSON file using PHP [closed]
  2. Add, Update, Delete and Read JSON Data/File in PHP
  3. Modifying a JSON file with PHP

JSON (../assets/data/maintenance.json)

[
    {
        "maintenance_status":"off"
    }
]

PHP (file_update.php)

<?php
$data = file_get_contents('../assets/data/maintenance.json');  // able to read file
$json_arr = json_decode($data, true);

$newValue = $_POST['newValue'];
foreach ($json_arr as $key => $value) {
    $json_arr[$key]['maintenance_status'] = $newValue;
}

file_put_contents('../assets/data/maintenance.json', json_encode($json_arr));
echo json_encode($json_arr); // return [{"maintenance_status":"on"}] at jQuery success response
?>

jQuery

$('.maintenance-toggle').on('click', function(){
    $('.maintenance-toggle').toggleClass('on');
    if ($('.maintenance-toggle').hasClass('on')){
        updateValue("on");
    }
    else if ($('.maintenance-toggle').hasClass('off')){
        updateValue("off");
    }
});

function updateValue(newValue) {
    console.log(newValue); // received "on" or "off"
    $.ajax({
        url : '../src/files/file_update.php',
        type : 'POST',
        data: { 
            newValue: newValue
        },
        cache: false,
        success: function(response){
            console.log(response); // success since received result from echo php but not update the value in JSON
        },
        error: function(e){
            
        }
    });
}

How do I restrict my uploaded files on a system to accept only zip files and word document files?

This is the line of code but I need help on how to go abour=t the issue above.

                <div class="col-lg-12">
                  <div class="form-group">
                    <label for="file" class="control-label text-muted">Project/ Thesis Document</label>
                    <input type="file" id="file" name="zip_file" class="form-control form-control-border" accept="application/zip" <?= !isset($id) ? "required" : "" ?> />
                  </div>
                </div>
              </div>```

Laravel Order results by conditional counting Pivot Table

I’ve a posts table with following structure

id title description
1 Post A Description A
2 Post B Description B

reactions table with following structure:

id title url
1 Like http://like_url
2 Dislike http://dislike_url

And post_reactions pivot table with following structure

post_id user_id reaction_id
1 1 1
1 2 1
2 1 2

How can I achieve posts table result OrderBy Max Count of ReactionID?

For e.g.

  • By ordering with reactionId = 1, the result should be:
[
  {
    id: 1,
    title: 'Post A',
    description: 'Description A'
    reaction_count: 2         // count of reactionId=1 is maximum here
  },
  {
    id: 2,
    title: 'Post B',
    description: 'Description B'
    reaction_count: 1         
  } 
]
  • By ordering with reactionId = 2, the result should be:
[
{
    id: 2,
    title: 'Post B',
    description: 'Description B'
    reaction_count: 1      // count of reactionId=2 is maximum here 
  },
  {
    id: 1,
    title: 'Post A',
    description: 'Description A'
    reaction_count: 2         
  },
]

What I’d tried is:

// Post Model
public function reactions(): BelongsToMany
    {
        return $this->belongsToMany(Reaction::class)->withPivot('user_id');
    }

// Controller
Post::with(['post_reactions' => function ($query) use ($reactionId) {
  $query->where('post_reactions.reaction_id', $reactionId)
        ->select(DB::raw('count(post_reactions.reaction_id) as reaction_count'))
        ->get();
}])->get();

Fatal error: Uncaught TypeError: mysqli_num_rows(): Argument #1 [duplicate]

I have an error on MySQL command which I have used in PHP command. here is the code

$sql1 ="SELECT CASE WHEN count1 = 0 THEN UPDATE tpl_loan SET loan_status='2' WHERE loan_app_no = '$loan_app_no' ELSE 'mis-matched' END 
                        FROM ( SELECT (SELECT COUNT(*) FROM tpl_loan_guarantor WHERE loan_app_no ='$loan_app_no' and status='1') AS count1 ) AS counts";
                        $results1 = mysqli_query($dbt,$sql1);
                        if(mysqli_num_rows($results1) > 0){
                        
                        
                         echo "<script>alert('You have a pending loan');</script>"; 
                        echo "<script>window.location.href='login'</script>";
                        
                        }

I get error

Fatal error: Uncaught TypeError: mysqli_num_rows(): Argument #1 ($result) must be of type mysqli_result, bool given

Please help me where I got I wrong

MySQL class / function to auto add tenant_id and userid to the query

I am trying to build a multi-tenant application, each customer will have their account setup on a subdomain1.example.com and subdomaion2.example.com.

The DB structure has all the data into single tables in single DB along with their domain name (tenant_id) and the user who inserted the data.

I wanted to know, what’s a better way to ensure that the tenant_id and the ownerid are automatically added to every crud.

eg: INSERT into table1 (value1,value2,value3)

and the tenant_id and the ownerid are automatically added

Error while installing wso2 wsf/php on Ubuntu 18.04

I’m currently trying to install the wso2 php extension on an Ubuntu 18.04 server. When I do the ‘make’ command, I’m getting the following error:

make[4]: Leaving directory '/home/mat/wso2-wsf-php-src-2.1.0/wsf_c/rampartc'
Making all in savanc
/bin/bash: line 17: cd: savanc: No such file or directory
Makefile:325: recipe for target 'all-recursive' failed
make[3]: *** [all-recursive] Error 1
make[3]: Leaving directory '/home/mat/wso2-wsf-php-src-2.1.0/wsf_c'
Makefile:221: recipe for target 'all' failed
make[2]: *** [all] Error 2
make[2]: Leaving directory '/home/mat/wso2-wsf-php-src-2.1.0/wsf_c'
Makefile:276: recipe for target 'all-recursive' failed
make[1]: *** [all-recursive] Error 1
make[1]: Leaving directory '/home/mat/wso2-wsf-php-src-2.1.0'
Makefile:206: recipe for target 'all' failed
make: *** [all] Error 2

I really need to install this extension. Thanks for help.