How to : Stream downloadable files using PHP and tell browser to save it instead of opening

index.php
<a href="download.php?file=docs/mydoc.doc"> Download </a>
download.php
<?php
$file_directory = "upload"; //Name of the directory where all the sub directories and files exists
$file = $_GET['file']; //Get the file from URL variable
$file_array = explode('/', $file); //Try to seperate the folders and filename from the path
$file_array_count = count($file_array); //Count the result
$filename = $file_array[$file_array_count-1]; //Trace the filename
$file_path = dirname(__FILE__).'/'.$file_directory.'/'.$file; //Set the file path w.r.t the download.php... It may be different for u
if(file_exists($file_path)) {
    header("Content-disposition: attachment; filename={$filename}"); //Tell the filename to the browser
    header('Content-type: application/octet-stream'); //Stream as a binary file! So it would force browser to download
    readfile($file_path); //Read and stream the file
else {
    echo "Sorry, the file does not exist!";
}
?>

Comments