Reputation: 283
Thus anyone has any idea why this code is not working for me
$type1 = $_FILES['textfield2']['type'];
$type2 = $_FILES['textfield3']['type'];
if($type1 == 'image/gif' || $type1 == 'image/png' && $type2 == 'image/gif' || $type2 == 'image/png')
{
echo 'Valid';
echo $type1.'<br />'.$type2;
}
else
{
echo 'Invalid';
}
If i select 1st file as a zip or any other format and then next as png it is going to valid that what i should not
Upvotes: 2
Views: 2301
Reputation: 101926
This is due to operator precedence. &&
has higher precedence than ||
so your expression results in:
$type1 == 'image/gif'
|| ($type1 == 'image/png' && $type2 == 'image/gif')
|| $type2 == 'image/png'
Use parentheses to make your intention clear:
($type1 == 'image/gif' || $type1 == 'image/png')
&& ($type2 == 'image/gif' || $type2 == 'image/png')
Additionally please note that the mime type is a client supplied data and thus is very easy to manipulate. Instead you should check for a valid GIF/PNG file header (using the GD library for example.)
Upvotes: 1
Reputation: 360632
PHP's operator precedence makes && bind tighter than ||, so your test is coming out as:
if($type1 == 'image/gif' || ($type1 == 'image/png' && $type2 == 'image/gif') || $type2 == 'image/png')
^----------------------------------------------^
Beyond that, do not use the user-provided ['type']
data for this. It's utterly trivial to forge, and someone can set to 'image/gif' while uploading nastyvirus.exe.
Upvotes: 2
Reputation: 21553
Try:
if(($type1 == 'image/gif' || $type1 == 'image/png') &&
($type2 == 'image/gif' || $type2 == 'image/png'))
{
echo 'Valid';
echo $type1.'<br />'.$type2;
}
else
{
echo 'Invalid';
}
This is due to operator precedence, which is documented here: http://php.net/manual/en/language.operators.precedence.php
Upvotes: 1