Tuesday, 16 April 2013

File Download Script in Php | PHP Tutorials for Beginners

In this tutorial of php code for beginners we will show you how to download any files from web server to local machine. When you want to download any file you need to send the file name to this application.

Step 1:-
Create index.html or any name for file and put the code in it. This is the html cede in which download link to the file is available. In download link pass the file name as query string. In bellow code "download.php" is the file where file downloading code is present. We are passing the file name of corresponding file which is to be downloaded.
<title>File download in php</title>
<tr><td><a href="download.php?file=download_file_in_php.jpg" class="links">Download file in php</a></td></tr>
<tr><td><a href="download.php?file=file_download.pdf" class="links">Download pdf</a></td></tr>

Step 2:-
Copy this code in a file and save it as "download.php". In above step when we click on link it will call the download.php file which is bellow. The bellow code recieve the file name which was sent in query string and process for downloading it. 


//path to the file.
//Your file should be in this folder only.

//Call the download function with file path,file name and file type
download_file($file_path, ''.$_REQUEST['file'].'', 'text/plain');

function download_file($file, $name, $mime_type='')

 if(!is_readable($file)) die('File not found.');

 $size = filesize($file);
 $name = rawurldecode($name);


  "pdf" => "application/pdf",
  "txt" => "text/plain",
  "html" => "text/html",
  "htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg"=> "image/jpg",
"jpg" =>  "image/jpg",
"php" => "text/plain"

$file_extension = strtolower(substr(strrchr($file,"."),1));
if(array_key_exists($file_extension, $known_mime_types)){
} else {


 // required for IE, otherwise Content-Disposition may be ignored
  ini_set('zlib.output_compression', 'Off');

 header('Content-Type: ' . $mime_type);
 header('Content-Disposition: attachment; file="'.$name.'"');
 header("Content-Transfer-Encoding: binary");
 header('Accept-Ranges: bytes');
 header("Cache-control: private");
 header('Pragma: private');
Hope this php tutorial is useful for you. Keep following PHP Tutorials for Beginners for more help.

1 comment: