PHP 文件上传:确保文件类型和大小限制
在 PHP 中,处理文件上传通常需要验证文件类型和大小限制。提供的代码片段尝试验证这两个标准,但遇到了问题。让我们深入研究代码并找出错误。
//check file extension and size
$resume = ($_FILES['resume']['name']);
$reference = ($_FILES['reference']['name']);
$ext = strrchr($resume, ".");
$ext1 = strrchr($reference, ".");
此代码捕获两个文件的文件名和扩展名。但后续的验证逻辑是有缺陷的:
if (!(
($_FILES["resume"]["type"] == "application/doc")
|| ($_FILES["resume"]["type"] == "application/docx")
|| ($_FILES["resume"]["type"] == "application/pdf")
&& (($_FILES["reference"]["type"] == "application/doc")
|| ($_FILES["reference"]["type"] == "application/docx")
|| ($_FILES["reference"]["type"] == "application/pdf"))
&& (($ext == ".pdf") || ($ext == ".doc") || ($ext == ".docx"))
&& (($ext1 == ".pdf") || ($ext1 == ".doc") || ($ext1 == ".docx"))
&& ($_FILES["resume"]["size"] 代码无法使用正确的逻辑来验证文件类型。它不检查 MIME 类型,而是依赖文件扩展名,这是不可靠的。此外,大小验证不适用于这两个文件。
为了纠正这些问题,这里有一个修改后的代码片段,它使用 MIME 类型并正确检查两个文件大小:
function allowed_file() {
$allowed = array('application/doc', 'application/pdf', 'application/docx');
if (in_array($_FILES['resume']['type'], $allowed) && in_array($_FILES['reference']['type'], $allowed)) {
if ($_FILES["resume"]["size"] 此代码首先检查文件的 MIME 类型是否包含在允许的列表中。如果是,则它会验证两个文件大小是否在指定限制内。这可确保仅接受允许的文件类型和大小进行上传。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3