I have gotten a problem about downloading .jpg and .avi files from a server using PHP I have the following code:
$fileName = "Koala.jpg";
$filePath = "./Koala.jpg";
if (!file_exists($filePath)){
echo "No file";
return;
}
$fp = fopen($filePath, "r");
$fileSize = filesize($filePath);
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Content-Length: $fileSize");
header("Content-Disposition: attachment;filename=".$fileName);
$buffer = 1024;
while(!feof($fp)){
$data = fread($fp, $fileSize);
echo $data;
}
fclose($fp);
The code downloads .txt file successfully and the downloaded file can be read. However, when it comes to .jpg, the downloaded .jpg file cannot be read. Can anyone give a helping hand? Thanks
Have just tried another method and it works fine
$file = 'Koala.jpg';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
But just wonder what reason causes the first method fail, even though using fopen("xxx", "rb") instead. Thank you