Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - send file to user

Tags:

php

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?

like image 477
Ian morgan Avatar asked May 21 '10 13:05

Ian morgan


3 Answers

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;
}
?>
like image 121
Adirael Avatar answered Nov 20 '22 15:11

Adirael


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.

like image 49
Rayjax Avatar answered Nov 20 '22 15:11

Rayjax


If you are using Apache or Lighty, then the "best" way to do this from a performance point of view, is to use the X-Sendfile header. See this tutorial: https://www.h3xed.com/programming/how-to-use-x-sendfile-with-php-apache

like image 5
chiborg Avatar answered Nov 20 '22 14:11

chiborg