PHP Readfile() not working for me and I don't know why

我的梦境 提交于 2019-11-29 16:41:45

If it's a big file, it cannot be sent with readfile. Try to use this:

  $handle = fopen($file_path, 'rb'); 
  $buffer = ''; 
  while (!feof($handle)) { 
    $buffer = fread($handle, 4096); 
    echo $buffer; 
    ob_flush(); 
    flush(); 
  } 
  fclose($handle); 

I am not sure why this worked, but I was able to solve this issue by breaking my php file into two pieces. Piece 1 loads WordPress and performs the logic validation. Then file 1 passes the information over to file 2 to do the download logic and write the header information.

Like I said, I am not sure why this worked, however a friend who knows PHP better than I do said that sometimes if the script takes too long to process then the headers won't take. It is possible that WordPress was hanging the script too long for these headers.

Hopefully this explanation will help someone else who is having this difficulty.

If you are trying to force browser to download the file with the use of

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="your-file.jpg"

but Chrome gives you ERR_FILE_NOT_FOUND and Firefox also fails with "Not found" (strangely Opera seems to work) try adding:

header('HTTP/1.0 200 OK', true, 200);

Chrome was telling me: "Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found." And Firefox as saying the file did not exist.

Although the same php file was handling a different type of download I was having issues with PNG and ICO, I tried some methods that only displayed the picture but did not prompt for a download box.

Finally I found out thanks to Crazycoolcam, that Wordpress was the issue. I was including a php to a file I had called "tools.php", inside of tools.php it had an include to wordpress's main header file, to remedy the issue I split my tools file into a wordpress version and a non wordpress version and included the wordpress half after it had written the file out.

Just another possibility here as to why its not working. This was the cause for me. Interestingly, file_exists was returning true but no form of serving the file to the public for download was working without having the below set correctly.

PHP has a setting called open_basedir

Make sure this is set correctly relevant to your hosting environment. open_basedir can be edited via php.ini

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!