Sinisterly
[PHP] Force file download - Printable Version

+- Sinisterly (https://sinister.ly)
+-- Forum: Coding (https://sinister.ly/Forum-Coding)
+--- Forum: PHP (https://sinister.ly/Forum-PHP)
+--- Thread: [PHP] Force file download (/Thread-PHP-Force-file-download)



[PHP] Force file download - 3541642 - 03-27-2012

Some files, such as mp3, are generally played throught the client browser. If you prefer forcing download of such files, this is not a problem: The following code will do that job properly.

Code:
function downloadFile($file){ $file_name = $file; $mime = 'application/force-download'; header('Pragma: public'); // required header('Expires: 0'); // no cache header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Cache-Control: private',false); header('Content-Type: '.$mime); header('Content-Disposition: attachment; filename="'.basename($file_name).'"'); header('Content-Transfer-Encoding: binary'); header('Connection: close'); readfile($file_name); // push it out exit(); }



RE: [PHP] Force file download - slbmeh - 03-31-2012

Really all you need it application/octet-stream as your mime type. That tells the browser that it is binary and cannot be displayed.

To do this in PHP you also need to provide 2 additional headers to follow HTTP specification.

The content disposition header set to attachment will tell the browser what to save it as... Instead of a random filename with query string like "whatever.php?d=12422&file=blah"

The content length header is required by HTTP 1.0, but not by HTTP 1.1, it is expected... If the file size cannot be determined it should be given the chunked attribute, this allows the HTTP 1.1 compliant client to determine if it has received the correct amount off data or not, and will return to the server whether or not it has.
PHP Code:
<?php header ("Content-type: octet/stream"); header ("Content-disposition: attachment; filename=".$file.";"); header("Content-Length: ".filesize($file)); readfile($file); exit;