duanlou2917
2017-12-10 00:33
浏览 88
已采纳

在PHP中使用scandir打开文件时“没有这样的文件或目录”

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
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongsui5464 2017-12-10 01:09
    已采纳

    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); 
    
    已采纳该答案
    打赏 评论
  • doujia4619 2017-12-10 00:57

    it is not related to the directory path, because in your state the path is probably correct. it depends on the file you are to read . since you are try to read a json file you get this message but if you put any other file it will be read . so you need to parse the json while reading like this

        $path = 'json/';
    $files = scandir($path);
    foreach ($files as $newest_file) {
        if ($newest_file === '.' or $newest_file === '..') continue;
        $data = json_decode(readfile($path.'/'.$newest_file));
        var_dump($data);
    }
    
    打赏 评论

相关推荐 更多相似问题