处理文件不存在时的404错误,核心在于在发送下载头之前检查文件路径的有效性。如果文件不存在,应直接调用http_response_code(404)设置状态码,输出错误提示并终止脚本,避免触发php的警告或尝试读取不存在的资源。

如何检测文件是否存在并返回404
使用file_exists()函数判断目标文件路径。若返回false,则立即设置HTTP 404状态码并退出。这是防止服务器报错和确保客户端收到正确错误码的标准做法。

<?php $file = '/path/to/missing.pdf';
if (!file_exists($file)) {
http_response_code(404);
die('File not found');
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
?>
如何处理文件存在但权限不足的情况
当file_exists()返回true但is_readable()返回false时,说明文件存在但当前用户无权访问。此时也应返回403 Forbidden或404 Not Found(视安全策略而定),通常建议返回403以明确告知权限问题,但在某些场景下为隐藏资源存在性可返回404。

<?php $file = '/path/to/unreadable.pdf';
if (!file_exists($file)) {
http_response_code(404);
die('File not found');
}
if (!is_readable($file)) {
http_response_code(403);
die('Access denied');
}
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
?>
基于程序中readfile()失败的具体问题
即使文件存在且可读,readfile()仍可能因磁盘I/O错误或内存限制而失败。此时应捕获异常或检查返回值,若返回-1表示失败,需记录日志并返回500 Internal Server Error,确保程序健壮性。
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











