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.