I'm trying to allow certain formats get uploaded to my website. I'm using the call getimagesize()
to identify the image type (which is returned as the third parameter). I followed this guide to perform that. Here's the code:
$img=$_FILES['img'];
$info = getimagesize($img);
if (($info[2] !== IMAGETYPE_GIF) && ($info[2] !== IMAGETYPE_JPEG) && ($info[2] !== IMAGETYPE_PNG)) {
echo json_encode(array('bad' => 'Bad Format'));
exit();
} else {
echo json_encode(array('good' => 'Good format'));
exit();
}
No matter what file format I try uploading, I always get the else
statement. echo json_encode(array('good' => 'Good format'));
Why is that happening, and how can I fix it?
it will always be false since you are using the &&
operator.
$img=$_FILES['img'];
$accepted = array('image/jpeg','image/png','image/gif');
if (in_array($img['type'],$accepted)) {
echo json_encode(array('bad' => 'Good Format'));
exit();
} else {
echo json_encode(array('good' => 'Bad format'));
exit();
}
use the ||
or or
to get what you want.
Doing it with getimagesize()
$img=$_FILES['img'];
$info = getimagesize($img['tmp_name']); //pass the file
Change your condition to ||
(or)
if (($info[2] === IMAGETYPE_GIF) || ($info[2] === IMAGETYPE_JPEG) || ($info[2] === IMAGETYPE_PNG)) {
echo json_encode(array('bad' => 'Good Format'));
exit();
} else {
echo json_encode(array('good' => 'Bad format'));
exit();
}