DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Kalatravas has posted 29 posts at DZone. View Full User Profile

How To Make Files Downloadable With PHP

  • submit to reddit
        In some situations when you’re creating a web page with links to a file like  pdf – xml – jpeg , or other external program file , you may want user’s browser  prompt  to download the file instead of opening it in the browser window or in an external program . There are a few different methods you can do this , my favorite is PHP-based . Start by creating a new file on your server or on your development computer called download.php  and paste the below code into the file .
Complete article :

// download.php
 if (isset($_GET['file'])) {
//$file = $_GET['file'];
$file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_ENCODED);
if (file_exists($file) && is_readable($file) && preg_match('/\.pdf$/',$file)) {
header('Content-Description: File Transfer');
header('Content-type: application/pdf');
header("Content-Type: application/force-download");// some browsers need this
header("Content-Disposition: attachment; filename=\"$file\"");
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file2));
}else {
header("HTTP/1.0 404 Not Found");
echo "<h3>Error 404: File Not Found: <br /><em>$file</em></h3>";
header('Refresh: 5; url=http://localhost/zy3.php');
print '<i style="color:red">You will be redirected in 5 seconds';
exit ;
} else {
header('Refresh: 5; url=http://localhost/zy3.php');
print '<h1 style="text-align:center">You you shouldn\'t be here ......</pre>
<p style="color: red;"><strong>redirection in 5 seconds</strong></p>


<a href="relative_path_to_this_file/download.php?file=example.pdf">Click here to download PDF</a>