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

时间:2017-12-10 00:33:10

标签: php xampp scandir

我想在名为“json”的文件夹中读取文件名最长的文件。

这是我的PHP :(内部文件“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); 
?>

“json”文件夹与“open.php”位于同一目录中。当我在我的服务器上运行它时,我得到一个响应false(或HTTP 500错误)。

当我在XAMPP上运行时,我得到:Warning: readfile(thisone.json): failed to open stream: No such file or directory in C:\xampp\htdocs\test\open.php on line 15
我不认为这是权限问题,因为我在Win 7上。我检查了文件夹和文件权限,所有用户都可以“阅读”。

问题:为什么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);
print_r($files);
$newest_file = $files[0];
print_r($newest_file);
readfile('/json/'.$newest_file); // corrected this, as @Jeff pointed out

我得到了输出:

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

<小时/> 相关SO问题:PHP - Failed to open stream : No such file or directory

2 个答案:

答案 0 :(得分:0)

它与目录路径无关,因为在您的状态中路径可能是正确的。这取决于你要阅读的文件。 因为您尝试读取json文件,所以您会收到此消息,但如果您放入任何其他文件,则会读取该消息。 所以你需要在阅读时解析json 像这样

    $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);
}

答案 1 :(得分:0)

scandir返回带有文件名的数组 - ,不带文件夹名称。

但是这里readfile($newest_file);你没有包含子文件夹(在编辑之前)

因此,在您的路径中包含所需的文件夹:

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