How to make PDF file downloadable in HTML link using PHP ?

To Download PDF from HTML link using PHP with the help of header() function in php. The header()function is used to send a raw HTTP header. Sometimes it wants the user to be prompted to save the data such as generated PDF.
Syntax:
header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="downloaded.pdf"');
header("Content-Length: " . filesize("download.pdf"));
readfile('original.pdf');
.
Note: Remember that HTTP header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file or from PHP.
Example 1: Save below HTML file as htmllinkpdf.html and save PHP file as downloadpdf.php
- Below example to illustrate concept of downloading PDF file using HTML link.
- Here downloading file appears to be PDF format but without any content which shows error on opening in any application
- HTML code:
<!DOCTYPE html><html>ÂÂ<head>Â Â Â Â<title>Download PDF using PHP from HTML Link</title></head>ÂÂ<body>Â Â Â Â<center>Â Â Â Â Â Â Â Â<h2style="color:green;">Welcome To GFG</h2>Â Â Â Â Â Â Â Â<p><b>Click below to download PDF</b>Â Â Â Â Â Â Â Â</p>Â Â Â Â Â Â Â Â<ahref="gfgpdf.php?file=gfgpdf">Download PDF Now</a></center></body>ÂÂ</html> - PHP code:
<?phpÂÂ$file=$_GET["file"] .".pdf";ÂÂ// We will be outputting a PDFheader('Content-Type: application/pdf');ÂÂ// It will be called downloaded.pdfheader('Content-Disposition: attachment; filename="gfgpdf.pdf"');ÂÂ$imagpdf=file_put_contents($image,file_get_contents($file));ÂÂÂecho$imagepdf;?> - Output:
Below example illustrates the concept of downloading PDF file locally (i.e. read gfgpdf.pdf file from local ) using HTML link.
Example 2: Save HTML file as htmllinkpdf.html and save PHP file as downloadpdf.php
- HTML code:
<!DOCTYPE html><html>ÂÂ<head>Â Â Â Â<title>Download PDF using PHP from HTML Link</title></head>ÂÂ<body>Â Â Â Â<center>Â Â Â Â Â Â Â Â<h2style="color:green;">Welcome To GFG</h2>Â Â Â Â Â Â Â Â<p><b>Click below to download PDF</b>Â Â Â Â Â Â Â Â</p>Â Â Â Â Â Â Â Â<ahref="downloadpdf.php?file=gfgpdf">Download PDF Now</a>Â Â Â Â</center></body>ÂÂ</html> - PHP code:
<?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();// This doesn't really matter.ÂÂ$fp=fopen($file,"r");while(!feof($fp)) {Â Â Â Âechofread($fp, 65536);Â Â Â Âflush();// This is essential for large downloads}ÂÂÂfclose($fp);Â?> - Output:
PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.



