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.
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
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With