ScopeXL Posted April 29, 2010 Share Posted April 29, 2010 Hello, I am trying to build a script that downloads a file from a specific location using a PHP header, though some of the files download as 0 bytes and are corrupted when extracted (if a .zip). Am I doing something wrong with these headers? if (file_exists("downloads/file.zip")) { error_reporting(E_ALL); header('Content-Encoding: none'); header('Accept-Ranges: bytes'); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=\"file.zip\""); header("Pragma: no-cache"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Content-Length: ".filesize("downloads/file.zip"); ob_clean(); flush(); readfile("downloads/file.zip"); exit; } Some files work, some are corrupted. I cannot wrap my head around whats causing this. I tried downloading the files straight from FTP and they are not corrupted so I'm fairly sure its the header. Any help would be appreciated. Thank you. Link to comment https://forums.phpfreaks.com/topic/200121-php-header-download-corrupts-some-files/ Share on other sites More sharing options...
mcjwb Posted April 29, 2010 Share Posted April 29, 2010 There are a few postings on the php manual page, http://uk.php.net/manual/en/function.readfile.php, about corrupt files that may help you. In particular, setting error_reporting to 0. Otherwise you could try opeining the corrupted file in a text editor and seeing if there is a readable error message in there. One other thing to note is the file size. Do the files that get corrupted have large/similar file sizes? If so you will need to send/download the file in chunks - there is a function on the php manual page that will do this for you. If none of the above helps, is there any other information/observations you can provide that may help dianose the problem? Link to comment https://forums.phpfreaks.com/topic/200121-php-header-download-corrupts-some-files/#findComment-1050372 Share on other sites More sharing options...
ScopeXL Posted April 29, 2010 Author Share Posted April 29, 2010 Ah, I was unaware their was a limit to what readfile() could handle. Thank you. For those with the same problem, I fixed with: $filename = '/path/to/file.ext'; if (filesize($filename) > 4194304) { // Forcibly end any output buffering going on. if (function_exists('ob_get_level')) { while (@ob_get_level() > 0) @ob_end_clean(); } else { @ob_end_clean(); } $fp = fopen($filename, 'rb'); while (!feof($fp)) { echo fread($fp, 8192); flush(); } fclose($fp); } else { readfile($filename); } Thanks again mcjwb. Link to comment https://forums.phpfreaks.com/topic/200121-php-header-download-corrupts-some-files/#findComment-1050392 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.