简体   繁体   中英

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.

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.

Since you are checking the type 3 times on different values, it is bound to always return true and thus trigger the if.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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