[英]Why is in_array() returning false always? php
Still getting the hang of PHP here. 仍然在这里使PHP陷入困境。 I've seen other questions similar to this but I can't figure out why mine is returning false.
我看过其他与此类似的问题,但我不知道为什么我会返回false。 I have a form that sends text and attaches files via email.
我有一个通过电子邮件发送文本并附加文件的表格。 The form sends the files as expected but once I started trying to validate for filetype I started only getting the error.
表单按预期方式发送文件,但是一旦我开始尝试验证文件类型,我就开始仅收到错误消息。 Why is my validation always returning false?
为什么我的验证总是返回false?
$error = False;
$file_type = $_FILES['upload']['type']; //returns the mimetype
$allowed = array("image/jpeg", "image/png", "image/gif", "application/pdf");
$total = count($_FILES['upload']['name']);
$attachments = "None";
$attachmentString = "No Attachments";
if(isset($_FILES['upload']['name']) && is_array($_FILES['upload']['name']) && count($_FILES['upload']['name']) > 0){
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
$uploaddir = trailingslashit( realpath(__DIR__) ) . 'uploads/';
wp_mkdir_p( $uploaddir );
//Setup our new file path
$newFilePath = $uploaddir . basename($_FILES['upload']['name'][$i]);
if(!in_array($file_type, $allowed)) {
$error = True;
echo "Error: Only jpg, gif, png, and pdf files are allowed.<br />";
}
else
{
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$attachments[$i] = $newFilePath;
//make string for mimetype headers in email
$attachmentString += implode($attachments[$i]) + ", ";
}
}
}
}
} }
When you update multiple files in PHP, the mimetype
of each files gets into the $_FILES['userfile']['type'][$i]
variable. 当您在PHP更新多个文件时,
mimetype
每个文件的获取到$_FILES['userfile']['type'][$i]
变量。
In your code, you check if the value of $_FILES['userfile']['type']
(which is array) exists in the $allowed
types (and this is always false). 在您的代码中,您检查
$_FILES['userfile']['type']
(是数组)的值是否在$allowed
类型中存在(且始终为false)。
You can change your code to: 您可以将代码更改为:
for($i=0; $i<$total; $i++) {
....
$file_type = $_FILES['upload']['type'][$i]; //returns the mimetype
....
if(!in_array($file_type, $allowed)) {
$error = True;
echo "Error: Only jpg, gif, png, and pdf files are allowed.<br />";
}
....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.