网站首页 文章专栏 PHP 强制下载文件
PHP强制下载文件
header() 函数向客户端发送原始的 HTTP 报头、然后自动下载文件。
若用得是如360浏览器、进入指定页面后就弹出文件下载对话框,如图
若是谷歌浏览器,会自动下载
封装成方法
/** * PHP 强制下载文件 * @param $archivo 服务器文件路径 * @param null $downloadfilename 下载文件名称 */ 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; } }