jump to navigation

How To Make Files Downloadable with PHP January 10, 2012

Posted by Tournas Dimitrios in PHP.
trackback

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 .


<?php

// download.php
 if (isset($_GET['file'])) {
//$file = $_GET['file'];// Always sanitize your submitted data!!!!!!
//$file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_ENCODED);// works also
$file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_SPECIAL_CHARS);
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($file));
ob_clean();
flush();
readfile($file);
    exit;
}else {
header("HTTP/1.0 404 Not Found");
echo "<h3>Error 404: File Not Found: <br /><em>$file</em></h3>";
header('Refresh: 5; url=./index.html');
print '<i style="color:red">You will be redirected in 5 seconds</i>';
exit ;
}
} else {
header('Refresh: 5; url=./index.html');
print '<h1 style="text-align:center">You you shouldn\'t be here ......</h1><br> <p style="color:red"><b>redirection in 5 seconds</b></p>';
exit;
}


?>

Into any file of your web-server’s directory structure create a hyperlink that points to download.php with the following code (My example assumes that both files are into the same directory ) :

//index.html
<!-- Your HTML code --> 
<a href="download.php?file=test1.pdf">Click here to download PDF</a><br>
<a href="download-multiple.php?file=test.pdf">Click here to download PDF via multiple.php</a><br>
<a href="download-multiple.php?file=test.swf">Click here to download a Flash via multiple.php</a>

Note :Never trust data that could be manipulated by visitor’s browser , so always sanitize it . In previous example , urlencode gets a specific external variable by name and optionally filters it .

Each file-type has it’s own “Header content-type” , the following script handles most used file-types :


<?php
//download multiple.php
if (isset($_GET['file'])) {
//$file = $_GET['file'];// Always sanitize your submitted data!!!!!!
//$file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_ENCODED);//works also
$file = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_SPECIAL_CHARS);
$fileType = pathinfo($file);
$returnType ;
if (file_exists($file) && is_readable($file)) { 

switch ($fileType['extension']) {
case "pdf" :
$returnType = "header('Content-type: application/pdf')";
break;
case "txt":
$returnType ="header('Content-type: text/plain')";
break;
case "html":
$returnType ="header('Content-Type: text/html; charset=utf-8')";
break;
case "htm":
$returnType ="header('Content-Type: text/html; charset=utf-8')";
break;
case "exe":
$returnType ="header('Content-Type: application/octet-stream')";
break;	
case "zip":
$returnType = "header('Content-Type: application/zip') ";	
break;
case "jpg":
$returnType ="header('Content-Type: image/jpeg')";
break;
case "jpeg":
$returnType ="header('Content-Type: image/jpeg')";
break;
case "gif":
$returnType ="header('Content-Type: image/gif')";
break;
case "png":
$returnType ="header('Content-Type: image/png')";
break;	
case "ppt":
$returnType ="header('Content-Type: application/vnd.ms-powerpoint')";
break;
case "xls":
$returnType ="header('Content-Type: application/vnd.ms-excel')";
break;
case "xml":
$returnType = "header('Content-Type: application/vnd.ms-xml') ";		
break;
case "mpeg":
$returnType ="header('Content-Type: audio/mpeg')";
break;
case "swf":
$returnType ="header('Content-Type: text/html; application/x-shockwave-flash')";
break;		
}
echo $returnType ; 
header('Content-Description: File Transfer');
echo $returnType ; 
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($file));
ob_clean();
flush();
readfile($file);
exit;
}else {
header("HTTP/1.0 404 Not Found");
echo "<h3>Error 404: File Not Found : <br /><em>$file</em></h3>";
header('Refresh: 5; url=./index.html');
print '<i style="color:red">You will be redirected in 5 seconds</i>';
}
}else {
header('Refresh: 5; url=./index.html');
print '<h1 style="text-align:center">You you shouldn\'t be here ......</h1><br> <p style="color:red"><b>redirection in 5 seconds</b></p>'; 
}

?>

Get complete source in zip format .
Reference link from StackOverflow.com .

Advertisements

Comments»

1. Compress –Zip– Multiple Files And Download with PHP « Tournas Dimitrios - January 10, 2012

[…] into one bundle ,  compressed as Zip file-format . If you have read my previous article ” How To Make Files Downloadable with PHP ” then you already know that PHP can “send-out”  raw HTTP headers to instruct […]

2. MK f - February 3, 2012

Nice weblog right here! Also your website lots up fast! What web host are you the use of? Can I get your associate hyperlink in your host? I want my web site loaded up as quickly as yours lol

tournasdimitrios1 - February 3, 2012

@Manchester
This blog is hosted on WordPress.com server .If you need specific information let me know 🙂

3. Prot - September 10, 2013

Great contribution! Works fine. Instructions are clear and script works as described. Good work.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s