我有一个上传表单,正在检查文件大小和文件类型,以将上传的文件限制为2 MB,以及.pdf,.jpg,.gif或.png文件类型。我的目标是在用户违反这些规则之一的情况下向他们显示警报消息。
有四种方案:
使用我当前的代码,即使文件类型正确(#3),当文件大小大于2兆字节(#4)时,它始终显示不正确的“类型”消息。
有什么想法吗?
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的文件,但是您的代码只能报告其中一个问题。尝试类似的方法:
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()有关更多信息,请参阅文档(称为“移动不存储”)。
move_uploaded_file()