PHP用户评论图片上传脚本遇超大文件无响应问题解决
解决PHP图片上传脚本超大小限制时无响应的问题
我是PHP新手,开发了一款用于用户评论的图片上传脚本,能验证文件是否为图片并检查文件大小。大部分功能正常,但当图片超过设定的3MB大小限制时,脚本完全无响应,加了调试输出语句也没法定位问题。
问题代码
ini_set("display_errors",1); error_reporting(E_ALL); date_default_timezone_set('America/New_York'); $date = date('m-d-Y_h.i.s_a', time()); $target_path = "/home/SOME_USER/WEB/SOME_SITE/comment/uploading/uploads/"; $filename = $date. "_" .basename( $_FILES['uploadedfile']['name']); $ext = pathinfo($filename, PATHINFO_EXTENSION); $test = preg_replace('/\.[^.\s]{3,4}$/', '', $filename); $newName = bin2hex($test); $target_path = $target_path."" . "$newName." .$ext; if (is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) { $mime_type = mime_content_type($_FILES['uploadedfile']['tmp_name']); $allowed_file_types = ['image/png', 'image/jpeg', 'image/gif']; if (! in_array($mime_type, $allowed_file_types)) { $url = "./index.php" . "?&message=Not an image"; header('Location: '.$url); } else { echo ('made it to this part ?'); return proceed(); } } function proceed() { global $target_path; global $newName; global $ext; echo 'made it here. . .'; if(isset($_FILES['uploadedfile']['name'])) { if($_FILES['uploadedfile']['size'] > 3145728) { //3mb) echo ('made it here #1'); $url = "./index.php" . "?&message=Too big !"; header('Location: '.$url); } else { if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { $url = "./index.php" . "?&message=" .$newName."." .$ext.""; header('Location: '.$url); } else{ echo('Made it here'); $url = "./index.php" . "?&message=Too big !"; header('Location: '.$url); } } } }
问题原因与解决方法
排查后发现核心问题:表单中设置的文件大小限制和脚本里的3MB(3145728字节)限制完全相同。当文件大小刚好等于或超过这个值时,浏览器会在上传阶段直接拦截请求,导致服务器端的脚本根本接收不到上传的文件,自然出现无响应的情况。
解决方法非常简单:将表单中的文件大小限制值调大1字节(比如设为3145729),让超过脚本限制的文件能正常传递到服务器,由脚本处理并返回「文件过大」的提示信息。
额外优化小提示
虽然当前问题已解决,但代码还有优化空间:
- 避免使用
global传递变量,改用函数参数传递更符合代码规范 - 执行
header('Location: ...')跳转后,记得加上exit()或die(),防止后续代码继续执行 - 检查PHP配置中的
upload_max_filesize和post_max_size,确保它们的值大于你的脚本限制,避免被PHP本身的配置拦截
内容的提问来源于stack exchange,提问作者WaXxX333
相关产品推荐
相关产品推荐

