Search code examples
phpxamppscandir

"No such file or directory" when opening file with scandir in PHP


I want to read the file with the longest file name in a folder called "json".

This is my PHP for that: (inside file "open.php")

<?php
// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding("UTF-8");
// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output("UTF-8");

$files = scandir( __DIR__ . '/json', SCANDIR_SORT_DESCENDING);
$newest_file = $files[0];
readfile($newest_file);
//$output = file_get_contents($newest_file);
//echo json_encode($output, JSON_HEX_TAG); 
?>

The "json" folder is in the same directory as "open.php". When I run this on my server, I get as a response false (or a HTTP 500 error).

When I run this on XAMPP, I get: Warning: readfile(thisone.json): failed to open stream: No such file or directory in C:\xampp\htdocs\test\open.php on line 15.
I don't think it's an issue with permissions since I'm on Win 7. I checked both folder and file permissions and all users can "read".

Question: Why is PHP failing to open the file? It correctly finds the file I want, but right afterwards tells me there is "no such file".


UPDATE:
Running the following code:

// Tell PHP that we're using UTF-8 strings until the end of the script
mb_internal_encoding("UTF-8");
// Tell PHP that we'll be outputting UTF-8 to the browser
mb_http_output("UTF-8");

$files = scandir( __DIR__ . '\\json', SCANDIR_SORT_DESCENDING);
print_r($files);
$newest_file = $files[0];
print_r($newest_file);
readfile('/json/'.$newest_file); // corrected this, as @Jeff pointed out

I get as output:

Array ( [0] => thisone.json [1] => .. [2] => . ) thisone.json
Warning: readfile(/json/thisone.json): failed to open stream: No such file or directory in C:\xampp\htdocs\test\open.php on line 18


Related SO question: PHP - Failed to open stream : No such file or directory


Solution

  • scandir returns and array with the filenames - without the folder name.

    But here readfile($newest_file); you didn't include the sub-folder (before your edit)

    So include the desired folder in your path:

    readfile('json\\'.$newest_file);