Wednesday, May 12, 2010

How to download file using PHP

The following is the code to download file using PHP



//Author : Parth Trivedi
if(isset($_GET['Action']) && $_GET['Action'] =='Download')
{
$speed = 100;
$export_file = "upload/".$_REQUEST['file'];
$file_extension = strtolower(substr(strrchr(basename($export_file),"."),1));
if(file_exists($export_file) && is_file($export_file) )
{
switch( $file_extension ) {
case "exe":$ctype="application/octet-stream";
break;
case "zip":$ctype="application/zip";
break;
case "mp3":$ctype="audio/mpeg";
break;
case "mpg":$ctype="video/mpeg";
break;
case "avi":$ctype="video/x-msvideo";
break;
// (sensitive stuff, like php files)
case "doc":$ctype="application/msword";break;
case "css":$ctype="text/plain";break;
case "htm":$ctype="application/force-download";break;
case "html":$ctype="application/force-download";break;
case "txt":$ctype="application/force-download";break;
default:
$ctype="application/force-download";
}
$filespaces = str_replace("_", " ", $export_file);
header("Cache-Control:");
header("Cache-Control: public");
header("Content-Type: $ctype");
header("Accept-Ranges: bytes");
$size = filesize($export_file);

header("Content-Length: ".$size);
header('Content-Disposition: attachment; filename="'.basename($filespaces).'"');
//open the file
$fp = fopen($export_file,"rb");
//seek to start of missing part
//start buffered download
while(!feof($fp)) {
//reset time limit for big file
set_time_limit(0);
print(fread($fp,1024*$speed));
flush();
sleep(1);
}
fclose($fp);
exit;
}
else
{
die("404 File not found!");
}
}

No comments: