PHP. PDF File Download

vicnumb Oct 12, 2012

Oct 12 2012 Published by under PHP & MySQL, Tricks

You have a pdf file with some informative info to share with your website users.

HTML Anchor, PDF File Download

Link your .pdf file into html code:

<a href="path_to_file/filename">download my file</a>

path_to_pdf_file – pdf file URL or relative path;
filename – your pdf file to download;

How does this work? Say your file is pdf, text, word, excel format… User’s browser automatically detects file type and display the file content to your users.
Now, to save this file they should click the right mouse button and select Save from the drop down menu.

But, what if you wish users download your file…

PDF File Download, PHP Solution

1. Insert download file anchor to your html code

<a href="download.php">download my file</a>

2. Create php file in the same folder

download.php

3. Insert the code below to your php file. Make sure you do the necessary modifications.

<?php
 
function download($filename){
 
  /*
  Example of filenames including relative path:
  downloads/filename.txt
  ../downloads/filename.pdf
 
  Example of filename including absolute path:
  /home/domain/public_html/downloads/archive.zip
  */
 
  /*make sure you remove older files with the same name from cache*/
  header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
  header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
  header("Content-Description: File Transfer"); //a descriptive name for download file operation
  header('Content-disposition: attachment; filename='.basename($filename)); //send to browser a command to download the file with the name basename($filename)
  header("Content-Type: ".filetype($filename)); //get the type of file to download - text, word, zip, pdf etc
  header("Content-Transfer-Encoding: binary"); //send file in binary mode
  header('Content-Length: '.filesize($filename)); //get the file size. Some browsers don't calculate file size, so it's not clear what is the final size of file that is being downloaded
  readfile($filename); //and finally get the file and run all options above
 
}
 
$filename = "/localfolders/filename"; //file name including local path. Path may be only local: relative or absolute (from root)
 
//call download function
download($filename);
 
?>

4. File download preventing errors
In order to avoid “headers already sent” error, you may want to add the following lines before readfile() command.

ob_clean(); 
flush();

5. Important: Make sure you don’t have any other conent on download page except your file.

Even a single echoed space on download page will be added to your file content. So after downloading your file will appear corrupted.

This solution works for any type of files browsers can read and display their content: images, text, word, excel, pdf, archives.

One response so far

Leave a Reply