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

在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); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度