download pdf from link php code example

Example: on click directly download pdf file in php

Download File Using PHP – Server Side Script
We will need to create PHP script file and pass the file name in the href attribute that we want to download as you can see below:

<a href="download.php?file=SampleFile.pdf" target="_new">Download File</a>
PHP Script

if (isset($_GET['file'])) {
$file = $_GET['file'];
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
 header('Content-Type: application/pdf');
 header("Content-Disposition: attachment; filename=\"$file\"");
 readfile($file);
 }
}
The above file will read the file name and trigger to force download. This example will work on all browsers

Tags:

Php Example