Reputation: 2492
I am trying to test if the uploaded file is the image type I want. If it isn't a gif,jpeg, png, it should echo "Problem". But when I execute this code, it always says there's a problem. What's wrong with my if statement?
$uploadfile_type=$_FILES['userfile']['type'];
if ( ($uploadfile_type !='image/gif') || ($uploadfile_type !='image/jpeg')
|| ($uploadfile_type !='image/png'))
{
echo 'Problem: file is not a gif or jpeg or png!';
exit;
}
This code works when I am only checking one type of image. Ex: if($uploadfile_type !='image/gif') --> this statement would work but when I add a OR it doesn't.
Upvotes: 0
Views: 213
Reputation: 40336
There's a riddle that goes:
I have two coins in my pocket. Their total value is thirty cents. One of them is not a nickel. What are they?
The answer is that they are a quarter and a nickel - the quarter satisfies the condition that "one of them is not a nickel". This is the kind of problem you are facing. Every file is not a gif
or is not a jpeg
- even the gifs and jpegs. The gifs are not jpegs
, and the jpegs are not gifs
. So, as others have said, you need to use AND
instead of OR
.
Upvotes: 2
Reputation: 22412
You should define a list of accepted mimetypes :
$accepted_types = array(
'image/gif',
'image/jpeg',
'image/png',
);
$uploadfile_type=$_FILES['userfile']['type'];
if (!in_array($uploadfile_type, $accepted_types))
{
echo 'Problem: file is not a gif or jpeg or png!';
exit;
}
I hope this will help, Jerome Wagner
Upvotes: 1
Reputation: 17977
Chad's answer is right.
If you want to shorten the code and make it prettier:
if (!in_array($uploadfile_type, array('image/gif', 'image/jpeg', 'image/png'))
{
// bad
}
Upvotes: 0
Reputation: 134167
You need to use AND instead of OR:
if ( ($uploadfile_type !='image/gif') && ($uploadfile_type !='image/jpeg')
&& ($uploadfile_type !='image/png'))
OR will always fail since a file will only ever be of a single type.
Upvotes: 0
Reputation: 74518
You're using OR (||
) when you should be using AND (&&
). You want to say there's a problem if it's not a GIF and it's not a JPG and it's not a PNG. With OR, the only way it wouldn't say there was a problem is if you had some sort of file that managed to be all 3 types at once.
Upvotes: 5