Home » Php » php failed to open stream when file exists

php failed to open stream when file exists

Posted by: admin October 26, 2017 Leave a comment

Questions:
$fileToAccess="userFiles/".$json[0]->userfor2.".json";
document.addEventListener('click', function(e)
{
   xhttp=new XMLHttpRequest();
   xhttp.onreadystatechange = function() 
   {
     if (this.readyState == 4 && this.status == 200) 
        {
            window.alert(this.responseText);
        }
   }
   xhttp.open("GET", "evaluate.php?q=[{\"id\": \""+e.target.id+"\"},{\"file\": \"<?php echo $fileToAccess;?>\"}]", true);
   xhttp.send();
   //alert(e.target.id)
});

and my getData.php:

<?php
    $file=$_REQUEST['q'];
    $myfile=file_get_contents($file);
    $json=json_decode($myfile);
    echo $json[1];
?>

Things I tried

added ./ in front of userFiles.

added__DIR__ before /userFiles

but I still get the error failed to open stream, even though I see the url displayed completely fine in the alert message and my file exists too

Permissions: chmod -R 777 on entire directory

EDIT: alert message:
This is the case using __DIR__
EDIT 2: after adding var_dump($file) in getData.php:
enter image description here
EDIT 3: after removing all spaces and ” from $file, I get the following alert: enter image description here

Answers:

In your PHP, try ‘realpath()’ function to reveal actually where your PHP code is looking for the file.

Also, use a ‘var_dump()’ to make sure your GET/POST variable names are correct as I am confused to see you are passing escaped double quotes in the URL.

Questions:
Answers:

I was you I’ll do something like that :

On $fileToAccess I’ll store only the file name not all the path

$fileToAccess=$json[0]->userfor2.".json";
document.addEventListener('click', function(e)
{
   xhttp=new XMLHttpRequest();
   xhttp.onreadystatechange = function() 
   {
     if (this.readyState == 4 && this.status == 200) 
        {
            window.alert(this.responseText);
        }
   }
   xhttp.open("GET", "evaluate.php?q=[{\"id\": \""+e.target.id+"\"},{\"file\": \"<?php echo $fileToAccess;?>\"}]", true);
   xhttp.send();
   //alert(e.target.id)
});

And set the path of the file in getData.php

<?php
  $file=$_REQUEST['q'];
  $myfile=file_get_contents(__DIR__.DS.userFiles.DS.$file);
  $json=json_decode($myfile);
?>