如何在 PHP 中限制文件上传类型的文件大小?
我有一个上传表单,正在检查文件大小和文件类型,以将上传的文件限制为 2 兆字节和 .pdf、.jpg、.gif 或 .png 文件类型.我的目标是在用户违反这些规则之一时向用户显示警告消息.
I have an upload form and am checking the file size and file type to limit the uploaded file to 2 megabytes and either .pdf, .jpg, .gif or .png file types. My goal is to have an alert message displayed to the user if they violate one of these rules.
有四种情况:
- 正确的尺寸/正确的类型(工作)
- 正确的尺寸/不正确的类型(工作)
- 尺寸不正确/类型正确(不起作用)
- 不正确的尺寸/不正确的类型(不起作用)
使用我当前的代码,当文件大小大于 2 兆字节 (#4) 时,它总是显示不正确的类型"消息,即使文件类型正确 (#3).
With my current code, it always displays the incorrect "type" message when the file size is greater than 2 megabytes (#4), even if the file type is correct (#3).
知道为什么吗?
if (isset ( $_FILES['uploaded_file'] ) ) {
$file_size = $_FILES['uploaded_file']['size'];
$file_type = $_FILES['uploaded_file']['type'];
if (($file_size > 2097152)){
$message = 'File too large. File must be less than 2 megabytes.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
elseif (
($file_type != "application/pdf") &&
($file_type != "image/jpeg") &&
($file_type != "image/jpg") &&
($file_type != "image/gif") &&
($file_type != "image/png")
){
$message = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
echo '<script type="text/javascript">alert("'.$message.'");</script>';
}
else {
store_uploaded_file($id);
}
}
您的代码未考虑到的问题是显示多个错误.正如您在上面提到的,用户上传的文件可能超过 2MB 的错误类型,但您的代码只能报告其中一个问题.尝试类似:
Something that your code doesn't account for is displaying multiple errors. As you have noted above it is possible for the user to upload a file >2MB of the wrong type, but your code can only report one of the issues. Try something like:
if(isset($_FILES['uploaded_file'])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES['uploaded_file']['size'] >= $maxsize) || ($_FILES["uploaded_file"]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if((!in_array($_FILES['uploaded_file']['type'], $acceptable)) && (!empty($_FILES["uploaded_file"]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) === 0) {
move_uploaded_file($_FILES['uploaded_file']['tmpname'], '/store/to/location.file');
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
}
die(); //Ensure no more processing is done
}
}
查看 move_uploaded_file()
的文档>(称为移动而不是存储)了解更多信息.
Look into the docs for move_uploaded_file()
(it's called move not store) for more.