Failed to open files as files damaged when download from PHP

206 views Asked by At

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.

1

There are 1 answers

2
Raptor On

The code can be simplified:

$file_name = '/path/to/MyFile.zip';
if(file_exists($file_name)) {
    header('Content-Type: application/octet-stream');
    header("Content-Transfer-Encoding: Binary"); 
    header("Content-disposition: attachment; filename=\"".$file_name."\""); 
    readfile($file_name);
    exit;
}

You have to make sure if the PHP can read the source file; recommended to use a relative path instead of an absolute path.