PHP - send file to user

I have a pdf file on disk that i need to send to a user when they make a request to a php script, what is the best way of doing this?


Solution 1:

Assuming that it's on the server:

readfile() — Outputs a file

NOTE: Just writing

readfile($file);

won't work. This will make the client wait for a response forever. You need to define headers so that it works the intended way. See this example from the official PHP manual:

<?php
$file = 'monkey.gif';

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, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}
?>

Solution 2:

Here is what you need to send a file with PHP :

$filename = "whatever.jpg";

if(file_exists($filename)){

    //Get file type and set it as Content Type
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    header('Content-Type: ' . finfo_file($finfo, $filename));
    finfo_close($finfo);

    //Use Content-Disposition: attachment to specify the filename
    header('Content-Disposition: attachment; filename='.basename($filename));

    //No cache
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');

    //Define file size
    header('Content-Length: ' . filesize($filename));

    ob_clean();
    flush();
    readfile($filename);
    exit;
}

As Julian Reschke commented, the validated answer MAY work, but it's full of useless headers. The content-type should be set to the real type of the file, or some browsers (especially mobile browsers) may not download it properly.