+40 745 232 788

Online Solutions Development Blog   |  

RSS

Force file download using php

posted by ,
Categories: PHP
Taggs , ,

If you want to provide the ability to download some content (like a text from the database) or to be sure that the browser won’t open a file you gave a like to instead of downloading it here are the few lines of php code that you can use to do that:

if(ini_get('zlib.output_compression'))
{
  ini_set('zlib.output_compression', 'Off');
}
$ctype="application/force-download";
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");
header("Content-Disposition: attachment; filename=\"export.txt\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".strlen($output));
echo $output;
exit();

In this context $output is a variable that holds the content of the file that you want the users to download. So you can create this variable by fetching some content from the database or getting the content of a file like this:

$output = file_get_contents('path/to/the/file');

Another point of interest in this example is this line:

header("Content-Disposition: attachment; filename=\"export.txt\";" );

You can replace “export.txt” with any file name that you want to use.

You can download this script using this link.

If you have any questions/comments please use the form below.

If you liked this post
you can buy me a beer

One Response to Force file download using php

Add a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Also, if you want to display source code you can enclose it between [html] and [/html], [js] and [/js], [php] and [/php] etc