Home > Article > Backend Development > PHP code to force file download
A piece of code in PHP that implements forced downloading of files. After entering the specified page, the file download dialog box pops up, just like the sudden meteor shower in a dream, which is quite cool, haha.
php code to force file download. <?php /** * Downloader * * @param $archivo * path al archivo * @param $downloadfilename * (null|string) el nombre que queres usar para el archivo que se va a descargar. * (si no lo especificas usa el nombre actual del archivo) * site http://bbs.it-home.org * @return file stream */ function download_file($archivo, $downloadfilename = null) { if (file_exists($archivo)) { $downloadfilename = $downloadfilename !== null ? $downloadfilename : basename($archivo); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $downloadfilename); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($archivo)); ob_clean(); flush(); readfile($archivo); exit; } } ?> The above code applies the processing method of PHP header file (header) information. If you have paid attention, you will find that most of the PHP forced file download codes collected by Programmer's Home use this method. . |