Thursday, March 10, 2011

Force Download with PHP

Hi,

Force downloading a file is commonly used in various asset management websites. The problem that a programmer faces is mainly with image or text files. If you put a simple hyperlink to a file, then on clicking the link it starts the download process automatically. But not for images or texts, because the image or text itself gets displayed in the browser, instead of downloading.

So in this code, no matter what ever your file its, it will always start the download process:

Step 1: create a hyperlink as follows:

<a href="download.php?file=my_pic.png">Download</a>

Step 2: create a "download.php" file in the same directory with the following:



<?php
session_start();
$file="my_asset/".$_GET['file'];
$ext=array_pop(explode(".",$file));
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$file");
SWITCH($extension) {
  case 'dmg':
    header('Content-Type: application/octet-stream');
    break;
  case 'exe':
    header('Content-Type: application/exe');
    break;
  case 'pdf':
    header('Content-Type: application/pdf');
    break;
  case 'sit':
    header('Content-Type: application/x-stuffit');
    break;
  case 'zip':
    header('Content-Type: application/zip');
    break;
  default:
    header('Content-Type: application/force-download');
    break;
}
header("Content-Transfer-Encoding: binary");
readfile($file);
?>

and you are done.

But this code is just for a basic idea. Be careful of not letting the end users to type in any file name in the URL and get them downloaded. It will not be safe. So I have given, "my_asset/". But again, this code is just to understand how force download works. Use it smartly while implementing.

Best,

No comments:

Post a Comment