简体   繁体   English

文件类型PHP验证

[英]File type PHP validation

What I am doing wrong with the code , it always shows 'File types .doc,.docx,.odt and max file size 2mb supported 'even if the file type is .doc format and size is 0kb. 我在代码中做的错误,即使文件类型为.doc格式且大小为0kb,它也始终显示“文件类型.doc,.docx,.odt和支持的最大文件大小为2mb”。

if(($_FILES["file"]["type"] != 'application/octet-stream') ||
            ($_FILES["file"]["type"] != 'application/vnd.oasis.opendocument.text')||
            ($_FILES["file"]["type"] != 'application/msword')||
            ($_FILES["file"]["size"] > 200000))
        {
            //echo $_FILES["file"]["size"];
            //echo $_FILES["file"]["type"];
            $this->assign_values('msg',"File types .doc,.docx,.odt and max file size 2mb supported");
            //echo "Error: " . $_FILES["file"]["error"] . "<br />";
        }

You need to change the || 您需要更改|| to && between the file types. &&在文件类型之间。 Or even better check the type against a list of allowed types: 甚至更好地根据允许的类型列表检查类型:

$allowedTypes = array('application/octet-stream', 'application/vnd.oasis.opendocument.text', 'application/msword');

if(!in_array($_FILES["file"]["type"], $allowedTypes) || $_FILES["file"]["size"] > 200000)
        {
            //echo $_FILES["file"]["size"];
            //echo $_FILES["file"]["type"];
            $this->assign_values('msg',"File types .doc,.docx,.odt and max file size 2mb supported");
            //echo "Error: " . $_FILES["file"]["error"] . "<br />";
        }

You are using OR, which means 1 of the parameters you gave has to be true. 您正在使用OR,这意味着您输入的参数之一必须为true。

Since you are checking the type 3 times on different values, it is bound to always return true and thus trigger the if. 由于您要在不同的值上检查类型3次,因此它一定总是返回true,从而触发if。

您正在使用OR(||),如果一个语句中的任何一个为true,则代码将执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM