readfile()
function file_force_download($file) { if (file_exists($file)) { // PHP, // ! if (ob_get_level()) { ob_end_clean(); } // header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); // readfile($file); exit; } }
readfile()
should not create memory problems. function file_force_download($file) { if (file_exists($file)) { // PHP, // ! if (ob_get_level()) { ob_end_clean(); } // header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header('Pragma: public'); header('Content-Length: ' . filesize($file)); // if ($fd = fopen($file, 'rb')) { while (!feof($fd)) { print fread($fd, 1024); } fclose($fd); } exit; } }
XSendFile On
function file_force_download($file) { if (file_exists($file)) { header('X-SendFile: ' . realpath($file)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file)); exit; } }
location /protected/ { internal; root /some/path; }
function file_force_download($file) { if (file_exists($file)) { header('X-Accel-Redirect: ' . $file); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . basename($file)); exit; } }
application/octet-stream
, but the real mime type of the file. For example, this will allow the browser to substitute the necessary programs in the file saving dialog.Source: https://habr.com/ru/post/151795/
All Articles