I am using PHP 7.3.22
in my Mac machine and I am trying to download files using PHP function. But I am unable to open the downloaded files as they are damaged. I am using the below code to download
function downloadFile()
{
$fileName = 'MyFile.zip';
$fullPath = '/path/to/MyFile.zip';
if(file_exists($fullPath)) {
header('Content-Description: File Transfer');
$contentType = mime_content_type($fullPath);
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Content-Type: '.$contentType);
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($fullPath)) . ' GMT');
header('Content-disposition: attachment; filename=' . $fileName);
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($fullPath)); // provide file size
header('Connection: close');
readfile($fullPath);
exit();
}
}
The download is not restricted for single file type. So getting the content type programatically
While opening the zip file after download, it is showing "Unadle to expand'MyFile.zip'. It is an unsupported format"
Am I doing something wrong here? Please help me to make this work. Any help could be appreciated.
The code can be simplified:
You have to make sure if the PHP can read the source file; recommended to use a relative path instead of an absolute path.