How to force download pdf files in PHP

Spread the love

Assuming the file exists on the file server and there is a path to access it, if we try to open the file in today’s modern browsers, most of them supports viewing the pdf files in the browser instead of downloading them.

So to overcome this problem, there is a simple way to download them by force.

Simply create a php file, in my example, i created download.php file. Use the following code as the content of download.php file.

<?php
	if(isset($_REQUEST['path']) && $_REQUEST['path'] != "") {

		$file_url = $_REQUEST['path'];
		$pdfname = basename ($file_url);
		header('Content-Type: application/pdf');
		header("Content-Transfer-Encoding: Binary");
		header("Content-disposition: attachment; filename=".$pdfname);
		readfile($file_url);
	}
?>

Above code expect a parameter named “path” which will have link to the pdf file. Once you pass the link of the file using this parameter to download.php, the pdf file will be downloaded forcefully.

You can try a quick demo using this link which opens the file in most of the browsers.

And using the above script, following demo link will download the same file instead of opening it in browser.