This tutorial will be very useful if you're trying to make some kind of downloading website or just want to download ordinary files instead of viewing them online.
[php]<?php
/*
added for security purposes. In case someone tries to download a file they aren't allowed to, the script will kill itself.
All you need to do is add this statement to the script that redirects here:
define("IS_DOWNLOAD","1");
As simple as that!
*/
if(defined(IS_DOWNLOAD))
{
die("HACKING ATTEMPT!");
}
$file = $_GET['file'];
$file_extension = strtolower(substr(strrchr($file,"."),1));
//did the user specify a file? if not, throw an error and kill the script
if(empty($file))
{
die("No file specified!");
}
//check if the file exists, if it doesn't, fire an error message and kill the script
if(!file_exists($file))
{
die("Specified file does not exist");
}
//checking through common file extensions
switch( $file_extension )
{
case "pdf":
$contenttype="application/pdf";
break;
case "exe":
$contenttype="application/octet-stream";
break;
case "zip":
$contenttype="application/zip";
break;
case "doc":
$contenttype="application/msword";
break;
case "xls":
$contenttype="application/vnd.ms-excel";
break;
case "ppt":
$contenttype="application/vnd.ms-powerpoint";
break;
case "gif":
$contenttype="image/gif";
break;
case "png":
$contenttype="image/png";
break;
case "jpg":
$contenttype="image/jpg";
break;
default:
$contenttype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // some browsers require this
//declares the type of file
header("Content-Type: $contenttype");
//declares the file as an attachment
header("Content-Disposition: attachment; filename=\"".basename($file)."\";" );
//the encoding of the transfer, duh?
header("Content-Transfer-Encoding: binary");
//the size of the file
header("Content-Length: ".filesize($file));
//ok here it is...tada!
readfile("$file");
//and thats it!
exit();
?>[/php]
Explanation:
I pretty much summed it up in all the comments. Remember to add the define() statement in your parent script or the script WILL NOT work!
You can download this script here: force-download.zip (0.99 kb)
Thanks!