How to force a file to download in PHP

If you want to force a download, you can use something like the following:

<?php
    // Fetch the file info.
    $filePath="/path/to/file/on/disk.jpg";

    if(file_exists($filePath)) {
        $fileName = basename($filePath);
        $fileSize = filesize($filePath);

        // Output headers.
        header("Cache-Control: private");
        header("Content-Type: application/stream");
        header("Content-Length: ".$fileSize);
        header("Content-Disposition: attachment; filename=".$fileName);

        // Output file.
        readfile ($filePath);                   
        exit();
    }
    else {
        die('The provided file path is not valid.');
    }
?>

If you simply link to this script using a normal link the file will be downloaded.

Incidentally, the code snippet above needs to be executed at the start of a page (before any headers or HTML output had occurred.) Also take care if you decide to create a function based around this for downloading arbitrary files – you’ll need to ensure that you prevent directory traversal (realpath is handy), only permit downloads from within a defined area, etc. if you’re accepting input from a $_GET or $_POST.

Leave a Comment