Suraj Hazarika
Suraj Hazarika

Reputation: 667

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 />";
        }

Upvotes: 2

Views: 2081

Answers (3)

Peter
Peter

Reputation: 3956

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 />";
        }

Upvotes: 4

Sumair Zafar
Sumair Zafar

Reputation: 98

You are using OR( || ) which if any of the one statement is true the code will execute

Upvotes: 0

Johan
Johan

Reputation: 1557

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.

Upvotes: 0

Related Questions