In this post, i want to explain download any file using php script. It will useful when we are developing a website like In that website have list of files and users can download those files. In my previous post i have explain how to get extension of file, using that post get the extension.
PHP Code
Script is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | <?php $filename = '[file name].[extension]'; $ctype="application/[extension]"; // required for IE, otherwise Content-disposition is ignored if(ini_get('zlib.output_compression')) ini_set('zlib.output_compression', 'Off'); header("Pragma: public"); // required header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); // required for certain browsers header("Content-Type: $ctype"); // change, added quotes to allow spaces in filenames header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($filename)); readfile("$filename"); exit(); ?> |
We can write this script for all types of files. We write this script in a function and just we pass the files with complete path. In this way we can use this script.
Hope it will be useful.



















Great…
thanks
Thanks for the code.
It works fine in Firefox and Google Chrome, but in IE. In IE, it downloads the php script itself.
I have put your code inside a separate file (namely download.php) and set it as the action of my form. Inside the form, two input elements are there – one gets the filename and the other is a submit button that sends the filename to ‘$filename’ in download.php. This is required as random files are there to download.
Please help. Thanks in advance.