I am confused about why this code says JPEG files and PNG files are invalid. I want this code to only accept JPEG and PNG, and deny all other file types, but right now, it's denying everything.
<?
echo '
<form method="post" action="upload.php">
<input type="text" placeholder="url" name="url" /> <input type="submit" value="check" name="submit" />
</form>
';
if (isset($_POST["submit"])) {
$url = $_POST["url"];
echo '<strong>URL:</strong> ' . $url;
echo '<br /><br />';
if(!filter_var($url, FILTER_VALIDATE_URL)) { //not valid f-in url
echo('Invalid url given');
} else {
if (exif_imagetype($url) != IMAGETYPE_JPEG || exif_imagetype($url) != IMAGETYPE_PNG) {
echo 'Invalid Image<br />';
} else {
echo "Works.";
}
}
}
?>
Your statement logic is backwards. This is essentially what you're writing:
$image_type = exif_imagetype($url);
if ($image_type != IMAGETYPE_JPEG || $image_type != IMAGETYPE_PNG) {
echo 'Invalid Image<br />';
} else {
echo "Works.";
}
Which translates to "if the image type isn't a JPEG or isn't a PNG, it's invalid". Instead, you want:
if( $image_type == IMAGETYPE_JPEG || $image_type == IMAGETYPE_PNG) {
echo "Works.";
} else {
echo "Invalid Image<br />";
}
Which is "if the image type is JPEG or PNG, it's valid", or:
if ($image_type != IMAGETYPE_JPEG && $image_type != IMAGETYPE_PNG) {
echo 'Invalid Image<br />';
} else {
echo "Works.";
}
"if the image isn't JPEG and it isn't PNG, it's invalid".
These conditions should be ANDed:
if (exif_imagetype($url) != IMAGETYPE_JPEG && exif_imagetype($url) != IMAGETYPE_PNG)
/* invalid image */
Read it like a sentence: if it's not a JPEG and it's not a PNG, it's invalid.
In addition, store the EXIF result in it's own variable and use that for a comparison instead of calling the method twice:
$itype = exif_imagetype($url);
if ($itype != IMAGETYPE_JPEG && $itype != IMAGETYPE_PNG)
/* invalid image */
!=
Means not equal. Remove that and use ==
.