in PHP

Force download of files in PHP

If you have files on your website that you want people to download you need to change the code to allow the browser to automatically download the file. This is because if you had an image on your website that you want people to download you can have a link to this image, but this will display the image on the browser. You need to change the header request to make the browser download this file instead of displaying the image. This is the same for PDF files and video files you need to change the header request to make the browser download the file. Here is a small PHP snippet which you can add a function which takes one parameter of the file path. This function will then read this file and automatically download the file.


function downloadFile($file){
        $file_name = $file;
        $mime = 'application/force-download';
    header('Pragma: public');   // required
    header('Expires: 0');       // no cache
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private',false);
    header('Content-Type: '.$mime);
    header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
    header('Content-Transfer-Encoding: binary');
    header('Connection: close');
    readfile($file_name);
    exit();
}

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email