[英]Why is in_array() returning false always? php
仍然在這里使PHP陷入困境。 我看過其他與此類似的問題,但我不知道為什么我會返回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]) + ", ";
}
}
}
}
}
當您在PHP更新多個文件時, mimetype
每個文件的獲取到$_FILES['userfile']['type'][$i]
變量。
在您的代碼中,您檢查$_FILES['userfile']['type']
(是數組)的值是否在$allowed
類型中存在(且始終為false)。
您可以將代碼更改為:
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.