PHP中使用!in_array判断值不在数组时出现空白页求助
解决文件上传错误处理时页面空白的问题
问题根源
你的代码存在变量作用域问题:全局声明的$errors数组在函数getFile()内部无法直接访问。当你在函数里执行$errors['fileformat'] = "Wrong file format!"时,实际是创建了一个局部的$errors数组,而全局的$errors始终为空。这导致count($errors) === 0永远成立,会强行执行sendMailWithAttachment()——如果此时文件格式不符合要求,这个函数可能抛出未被捕获的错误,最终导致页面空白。
修复方案
有两种简单方式解决作用域问题:
方案1:在函数内声明使用全局变量
修改getFile()函数,在开头添加global $errors,明确告诉PHP要使用全局的$errors数组:
function getFile( $filename , $formData ) { global $errors; // 声明使用全局变量 $allowedExts = array("pdf"); $temp = explode(".", $_FILES["uploaded_file"]["name"]); $extension = end($temp); $mimes = array('application/pdf'); if (!in_array($_FILES['uploaded_file']['type'],$mimes ) || !in_array($extension, $allowedExts, true)) { $errors['fileformat'] = "Wrong file format!"; } // 后续代码不变 }
方案2:通过引用传递$errors数组
把$errors作为参数传入函数,并使用引用传递(加&符号),这样函数内的修改会直接作用于全局数组:
// 修改函数定义,添加引用参数 function getFile( $filename , $formData, &$errors ) { $allowedExts = array("pdf"); $temp = explode(".", $_FILES["uploaded_file"]["name"]); $extension = end($temp); $mimes = array('application/pdf'); if (!in_array($_FILES['uploaded_file']['type'],$mimes ) || !in_array($extension, $allowedExts, true)) { $errors['fileformat'] = "Wrong file format!"; } // 后续代码不变 } // 调用函数时传入$errors $name_of_uploaded_file =basename($_FILES['uploaded_file']['name']); getFile( $name_of_uploaded_file, $formData, $errors );
额外建议
- 开启错误提示:在脚本开头添加以下代码,方便排查问题,避免页面空白:
error_reporting(E_ALL); ini_set('display_errors', 1);
- 不要依赖$_FILES['type']:这个值由客户端提供,可能被篡改。建议用PHP的
finfo扩展做服务器端MIME类型验证:
$finfo = new Finfo(FILEINFO_MIME_TYPE); $fileMime = $finfo->file($_FILES["uploaded_file"]["tmp_name"]); if (!in_array($fileMime, $mimes) || !in_array($extension, $allowedExts, true)) { $errors['fileformat'] = "Wrong file format!"; }
内容的提问来源于stack exchange,提问作者crally
相关产品推荐
相关产品推荐

