Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download existing file in PHP

I have a pdf file on my server. I want to create such link that, user can click on it and download that pdf file. I am using Zend frame work with Php.

like image 483
Muhammad Zeeshan Avatar asked Dec 09 '22 14:12

Muhammad Zeeshan


2 Answers

place this code inside a php file and call it f.e. "download.php":

<?php

$fullPath = "path/to/your/file.ext";

if ($fd = fopen ($fullPath, "r")) {

    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);

    header("Content-type: application/pdf");
    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");            
    header("Content-length: $fsize");
    header("Cache-control: private");

    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
    }
}

fclose ($fd);
exit;

?>

Example: place this kind of link into the document where the file download is offered:

<a href="download.php?download_file=some_file.pdf">Download here</a>

More Detail:

http://www.finalwebsites.com/forums/topic/php-file-download

like image 59
Naveed Avatar answered Dec 26 '22 16:12

Naveed


I assume there is a reason you can't just link to the pdf directly, such as the need to authenticate the user. In that case, you will need to set the correct headers, and, as others have noted, you can use get_file_contents to serve the pdf. However, using get_file_contents requires that you read the file into memory before you send the response. If the file is large, or if you receive many requests at once, you can easily run out of memory. A great solution if you're using Apache or Lighttpd is to use XSendFile. With XSendFile you set the X-Sendfile response header to the file's path, and your web server serves the file directly from disk - without revealing the file's location on disk.

The problem with this solution is that the module must be installed on Apache, and it must be configured to work with Lighttpd.

Once XSendFile is installed, your Zend Framework action code would look something like the following:

// user auth or other code here -- there has to be a reason you're not
// just pointing to the pdf file directly

$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();

$this->getResponse()->setHeader('Content-type', 'application/pdf')
                    ->setHeader('X-Sendfile', 'path-to-file')
                    ->sendResponse();
like image 39
Isaac Avatar answered Dec 26 '22 16:12

Isaac