开发者

Why the following upload if condition does not work?

So I have an upload script, and I want to开发者_开发知识库 check the file type that is being uploaded. I only want pdf, doc, docx and text files

So I have:

$goodExtensions = array('.doc','.docx','.txt','.pdf', '.PDF');
$name = $_FILES['uploadFile']['name'];
$extension = substr($name, strpos($name,'.'), strlen($name)-1);


 if(!in_array($extension,$goodExtensions) || (($_FILES['uploadFile']['type'] != "applicatioin/msword") || ($_FILES['uploadFile']['type'] != "application/pdf"))){
     $error['uploadFile'] = "File not allowed. Only .doc, .docx, .txt and pdf";
 }

Why I'm getting the error when testing and including correct documents?


Since you are using OR instead of AND in your expression:

 if (!in_array($extension,$goodExtensions)
     || (($_FILES['uploadFile']['type'] != "applicatioin/msword")
         || ($_FILES['uploadFile']['type'] != "application/pdf"))) {
     $error['uploadFile'] = "File not allowed. Only .doc, .docx, .txt and pdf";
 }

this always evaluates to true: if the file extension is listed in the array goodExtensions, the first expression is false. However, since the file type can not be both Word and PDF at the same time, the second bracketed expression is always true.

So if you want to ensure that either the file extension or the MIME type is good, the correct expression would be (including the fix for the typo in "applicatioin/msword"):

 if (!in_array($extension,$goodExtensions)
     || (($_FILES['uploadFile']['type'] != "application/msword")
         && ($_FILES['uploadFile']['type'] != "application/pdf"))) {
     $error['uploadFile'] = "File not allowed. Only .doc, .docx, .txt and pdf";
 }


The third parameter for substr is the length, not the end position. If you want everything up until the end of the string just omit the third parameter entirely:

$extension = substr($name, strpos($name,'.'));

You've also spelt application wrong in applicatioin/msword.

Finally, you might want to use strrpos instead of strpos, in case the filename contains other dots before the one separating the extension.

Edit: the logic in the if statement is wrong as well. You error if either the extension isn't known, or the type is not MS Word, or the type is not PDF. The type can't be both of those at once, so it'll always fail. You want the last || to be a &&, I think.


Probably because one (or more) of those 3 conditions in the if statement returns true.


Why I'm getting the error when testing and including correct documents?

I don't know, but you would do well to take the big "if" apart into singular blocks to find the error.

Make test outputs of the MIME type and file extension.

echo "Extension = ".$extension."<br>";
echo "MIME Type = ".$_FILES['uploadFile']['type']; 

Also, one thing that jumps the eye is a typo in applicatioin/msword.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜