php实现下载
PHP 实现文件下载的方法
使用 header() 和 readfile()
通过设置 HTTP 头信息并直接输出文件内容实现下载功能。
$file_path = 'path/to/file.pdf';
$file_name = 'custom_name.pdf';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
分块下载大文件
对于大文件,使用分块读取避免内存溢出。

$file_path = 'path/to/large_file.zip';
$chunk_size = 1024 * 1024; // 1MB per chunk
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
exit;
强制下载非本地文件
从远程 URL 下载并直接转发给用户。
$remote_url = 'https://example.com/file.zip';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="downloaded.zip"');
readfile($remote_url);
exit;
安全注意事项
-
验证文件路径防止目录遍历攻击:

$base_dir = '/safe/directory/'; $user_path = $_GET['file']; $real_path = realpath($base_dir . $user_path); if (strpos($real_path, $base_dir) === 0 && file_exists($real_path)) { // 安全下载逻辑 } -
对于敏感文件,建议存储在 web 根目录之外并通过 PHP 脚本代理访问。
处理浏览器缓存
添加随机参数强制浏览器重新下载:
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");






