What I am trying to implement is force download of a file through PHP.
There are 2 issues that I am facing, and I’ve broken my head thinking about what is possibly going wrong here.
- Whenever I try to download the file using IE, the download gets interrupted about midway i.e. say my file is 1024Kb in size, around 500Kb is when the download stops as I get an error message in IE say ‘Download was interrupted’
- The other issue that I encounter frequently (but not always) is that the downloaded file (which is actually a zip file) gets corrupted at times for some reason! The file on the server is alright – if I download it directly from there, no issues at all. However, if I download using my PHP script and then try to unzip the file – Windows says ‘Invalid or corrupt file…’
I really need some help on this.
Following is the block of code downloading the file:-
$fileName = "./SomeDir/Somefile.zip";
$fsize = filesize($fileName);
set_time_limit(0);
// required for IE, otherwise Content-Disposition may be ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// set headers
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-type: application/zip');
header("Content-Disposition: attachment; filename=\"".basename($fileName)."\";");
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
header("Content-Length: " . $fsize);
// download
$file = @fopen($fileName,"rb");
if ($file) {
while(!feof($file)) {
print(fread($file, 1024*8));
flush();
if (connection_status()!=0) {
@fclose($file);
die();
}
}
@fclose($file);
}
Try this