答案是实现PHP文件下载需正确设置响应头并保障安全。首先通过header()设置Content-Type、Content-Disposition等头部,确保浏览器以附件形式下载;使用ob_clean()清除缓冲区,readfile()输出文件内容。针对中文文件名乱码,需根据用户代理对filename进行rawurlencode编码,兼容IE等浏览器。安全性方面,应将文件存于Web目录外,验证路径合法性,防止目录遍历,过滤用户输入。大文件可采用分段读取降低内存消耗,最终实现稳定安全的下载功能。

实现PHP文件下载功能,关键在于正确设置HTTP响应头信息,告诉浏览器不要直接打开文件,而是将其作为附件下载。同时要确保文件路径安全、文件存在且可读。
通过header()函数发送特定的响应头,控制浏览器行为:
示例代码:
$filePath = 'uploads/example.pdf';
$fileName = basename($filePath);
if (file_exists($filePath) && is_readable($filePath)) {
// 清除缓冲区防止输出干扰
ob_clean();
flush();
// 设置头信息
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . urlencode($fileName) . '"');
header('Content-Length: ' . filesize($filePath));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
// 输出文件内容
readfile($filePath);
exit;
} else {
http_response_code(404);
echo "文件未找到或不可读。";
}
直接使用中文文件名可能导致下载时乱码。推荐做法是统一用英文名,或根据浏览器兼容方式编码:
立即学习“PHP免费学习笔记(深入)”;
改进的文件名设置:
$ua = $_SERVER['HTTP_USER_AGENT'];
$encodedName = rawurlencode($fileName);
if (preg_match('/MSIE|Trident/', $ua)) {
header('Content-Disposition: attachment; filename="' . $encodedName . '"');
} else {
header('Content-Disposition: attachment; filename="' . $fileName . '"; filename*=UTF-8\'\'' . $encodedName);
}
避免暴露服务器路径,防止目录遍历攻击:
基本上就这些。核心是头信息设置准确,配合路径安全检查,就能稳定实现文件下载功能。
以上就是PHP代码怎么实现文件下载功能_PHP文件下载头信息设置方法的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号