Want to make PDF file downloadable in HTML link in PHP? Instead of linking to the .PDF file, instead do something like:
1 | <a href="pdf_server.php?file=pdffilename">Download my eBook</a> |
Which outputs a custom header, opens the PDF (binary safe) and prints the data to the user’s browser, then they can choose to save the PDF despite their browser settings. The pdf_server.php should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | header("Content-Type: application/octet-stream"); $file = $_GET["file"] .".pdf"; header("Content-Disposition: attachment; filename=" . urlencode($file)); header("Content-Type: application/octet-stream"); header("Content-Type: application/download"); header("Content-Description: File Transfer"); header("Content-Length: " . filesize($file)); flush(); // this doesn't really matter. $fp = fopen($file, "r"); while (!feof($fp)) { echo fread($fp, 65536); flush(); // this is essential for large downloads } fclose($fp); |
PS: and obviously run some sanity checks on the “file” variable to prevent people from stealing your files such as don’t accept file extensions, deny slashes, add .pdf to the value.
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.