Jack Barber Design & Technology

01947 878108 info@jackbarber.co.uk

How Can I Create a PDF File Download in PHP?

I've recently been working on the new Whitby Town Council website.  One of the main requirements of the council was that PDF documents should be available to download from a number of document categories.  At the same time, some of the documents should only be available to town councillors, with others freely available to the general public.

To get round the issue of someone trawling the file system for downloads, the PDFs are uploaded into randomly named directories, and with directory listing off, it should be pretty difficult for anyone to get their hands on files.  However, in order the hide the location of the PDF, I needed to server the file as a download via PHP, rather than providing a direct link to the file.

I spent quite a while working out the most efficient and reliable method - as there is a number of suitable solutions to this issue.  The most reliable (and simplest) method I found was this:

header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=' . $FileName);
readfile($FileURL);

$FileName is the filename of the PDF you wish to serve as a download.

$FileURL is the exact URL of the file to serve as a download.

So that's it.  My PHP function basically generates the $FileURL value from data stored in a database, the header() functions tell your browser what kind of file it's opening and the readfile() bit offers the file for download, without declaring the location of the file on the server.

I'm sure there are more secure variations for this - any ideas welcome, feel free to comment below.