为什么in_array()总是返回false?php

为什么in_array()总是返回false?php,php,forms,Php,Forms,这里仍然掌握着PHP的窍门。我见过其他类似的问题,但我不明白为什么我的答案是假的。我有一个表格,通过电子邮件发送文本和附加文件。表单按预期发送文件,但一旦我开始尝试验证文件类型,我只会收到错误。为什么我的验证总是返回false $error = False; $file_type = $_FILES['upload']['type']; //returns the mimetype $allowed = array("image/jpeg", "image/png", "image/gif",

这里仍然掌握着PHP的窍门。我见过其他类似的问题,但我不明白为什么我的答案是假的。我有一个表格,通过电子邮件发送文本和附加文件。表单按预期发送文件,但一旦我开始尝试验证文件类型,我只会收到错误。为什么我的验证总是返回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]) + ", ";
            }
        }

   }
}
$error=False;
$file\u type=$\u文件['upload']['type']//返回mimetype
$allowed=数组(“image/jpeg”、“image/png”、“image/gif”、“application/pdf”);
$total=计数($_文件['upload']['name']);
$attachments=“无”;
$attachmentString=“无附件”;
如果(设置($_文件['upload']['name'])和&is_数组($_文件['upload']['name'])和计数($_文件['upload']['name'])大于0){
//循环浏览每个文件

对于($i=0;$i当您在PHP中更新多个文件时,每个文件的
mimetype
会进入
$\u文件['userfile']['type'][$i]
变量

在代码中,检查
$\u 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 />";
    }
    ....
}

for($i=0;$itry to
var\u dump($file\u type)
看看它是否正确。
$file\u type
是数组。如果你打印出来,你会看到它。但是今天谁在调试呢?在in\u数组之前echo$file\u type给了你什么?你可能还需要将image/jpg添加到你的文件类型arrayit是。我甚至尝试过使用in\u数组(“image/png”,允许使用$);而且我还是错了。很明显,我在这里遗漏了一些东西。不要想当然地认为
$\u FILES['upload']['type']
的价值,本质上,它的浏览器生成的数据不必存在,而且可以被操作,因此您的脚本并不真正安全。感谢您修复了它!