Wednesday, August 21, 2013

PHP: step by step example to do a download manager web page

Some info should be concerned before you begin to do a download manager program:
1. Bandwidth of your host
2. Download speed
3. Capacity of server
4. File is stored in folder or Database? If it is store in DB, should concern about capacity of DB
5. Download statistic

The first program
//file download.php
<?php
 $filename = "document.zip";
 $fp = fopen($filename, "rb");

 header("Content-type: application/octet-stream");
 header("Content-length: " . filesize($filename));

 fpassthru($fp);
 fclose($fp);
 ?>

It's too simple, sure! The first program will read document.zip file in server then save it on client (PC of user) as download.php file as default. You must rename it with correct extension name to open it in client PC.

The second program
Next step, we'll make the program download a file on a specific folder on server then save it in the same name in client, e.g. we want to download and save file with name document.zip on server, we will call download.php?file=document.zip
//file download.php
<?php
 //default folder on server that contains files which are allowed to download
 $upload_dir = "../upload/";

 //get download file name
 $filename = isset($_GET['file'])?$_GET['file']:'';

 //check the file
 if ( !preg_match('/^[a-z0-9\_\-][a-z0-9\_\-\. ]*$/i', $filename) )
         || !is_file($upload_dir.$filename) || !is_readable($upload_dir.$filename) ) {
     echo "Error: invalid file name or not existing!";
     exit(-1);
 } //end if

 //open in binary mode and read the file
 $fp = fopen($upload_dir.$filename, "rb");

 //send header to the browser in client side
 header('Content-type: application/octet-stream');
 header('Content-disposition: attachment; filename="'.$filename.'"');
 header('Content-length: ' . filesize($upload_dir.$filename));

 //get and save file
 fpassthru($fp);
 fclose($fp);
?>

It is still too easy, sure!

Where I can use this download manager
-Use it in the case of you don't want publish the direct location to download the file
-Use it in next step of a login progress, in which you allow user download a file after paying credit
-Use it if you want to track activity of user. This requires small modification to save time stamp + user + client ip + download file name to a log file or DB.

When we shouldn't use it
-Server is overloading
-File is too big
-File is not important

Hope it can help you start a bigger program -:)

1 comment:

Subscribe to RSS Feed Follow me on Twitter!