PHP: Force PDF file to download.

This is a short guide on how to force a PDF file to download using PHP. In this guide, I will show you how to force the browser to download the PDF file as an attachment instead of displaying it directly.

Take a look at the following PHP script:

//The full or relative path to your PDF file.
$pdfFile = 'instructions.pdf';

//Set the Content-Type to application/pdf
header('Content-Type: application/pdf');

//Set the Content-Length header.
header('Content-Length: ' . filesize($pdfFile));

//Set the Content-Transfer-Encoding to "Binary"
header('Content-Transfer-Encoding: Binary');

//The filename that it should download as.
$downloadName = 'instructions.pdf';

//Set the Content-Disposition to attachment and specify
//the name of the file.
header('Content-Disposition: attachment; filename=' . $downloadName);

//Read the PDF file data and exit the script.
readfile($pdfFile);
exit;

In the code above:

  • We referenced the path to the PDF file that we want to download. In this case, the file in question isĀ instructions.pdf and it is located in the same directory as our PHP script. It is important to note that you can also use a full path to your PDF if the file is located in another directory.
  • We used PHP’s header function to set the Content-Type response to “application/pdf“. This header tells the browser what type of data it should expect.
  • The Content-Transfer-Encoding header was set to “Binary” because we want to transfer the file in its natural binary format.
  • We specified what filename should be used when the file is downloaded. This is the name that will be displayed when the user is prompted to download the file. Note that this does not have to be the same name as the original filename. For example: You could add the current date to the filename if that makes sense.
  • Using PHP’s filesize function, we were able to calculate the size of the file in bytes and set that as the Content-Length header.
  • The Content-Disposition header was set to “attachment”. As a result, the client’s browser will now know that it should treat the data as a file download.
  • Finally, we outputted the data of our PDF file using PHP’s readfile function.

That’s it! Pretty simple, right?