This tutorial will discuss the steps to make your PDF files downloadable in HTML links with PHP. We will use the PHP header() function to prompt users to save our PDF file.
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="Delft.pdf"');
header("Content-Length: " . filesize("Delft.pdf"));
We will attempt to download a PDF( Delft.pdf ) in HTML with a PHP script in the following example. The Delft.pdf file is empty and will show an error upon opening, and we’ll give you a picture of how we go about the process.
Example Code - HTML script:
html> head> title>Download PDF using PHP from HTML Linktitle> head> body> center> h2 style="color:red;">Welcome To DELFTh2> p>b>Click below to download PDFb>p> a href="downloadpdf.php?file=Delft">Download PDF Nowa> center> body> html>
Example Code - PHP script:
php $file = $_GET["file"] .".pdf"; // To Output a PDF file header('Content-Type: application/pdf'); // PDF will be called Delft.pdf header('Content-Disposition: attachment; filename="Delft.pdf"'); $imagpdf = file_put_contents($image, file_get_contents($file)); echo $imagepdf; ?>
The link will download a Delft.pdf file, but since the file is empty, we will get an error when trying to open it. That is the basic concept of downloading PDF files in HTML links with PHP.
Let’s try downloading and reading the Delft.pdf file from our local machine. In the next example, we will attempt to download a PDF file locally with an HTML link.
Example Code - HTML Script:
html> head> title>Download PDF using PHP from HTML Linktitle> head> body> center> h2 style="color:blue;">Welcome To DELFTSTACKh2> p>b>Click below to download PDFb>p> a href="downloadpdf.php?file=Delft">Download PDF Nowa> center> body> html>
Example Code - PHP Script:
php header("Content-Type: application/octet-stream"); $file = $_GET["file"] . ".pdf"; header("Content-Disposition: attachment; filename=" . urlencode($file)); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($file)); flush(); // Not a must. $fp = fopen($file, "r"); while (!feof($fp)) echo fread($fp, 65536); flush(); // This is essential for large downloads > fclose($fp); ?>
The link will download the Delft.pdf file, and we successfully open the file. Always call headers before sending output.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.