Check if the image is JPEG
I need to check if a given image is JPEG.
if ($_FILES["fname"]["error"] > 0) { $imgData = "hyperlink/holder.jpg"; } else { $imgData ="hyperlink/" . $_FILES["fname"]["name"]; } // Only accept jpg images // pjpeg is for Internet Explorer should be jpeg if (!($_FILES["fname"]["type"] == "image/pjpeg") ) { print "I only accept jpg files!"; exit(0); } When it jumps to the first expression in the first if statement, it always gives me only jpg files.
How can i fix this?
Try the exif_imagetype image function.
Example:
if(exif_imagetype($filepath) != IMAGETYPE_JPEG){ echo 'Not a JPEG image'; } Check the mime file type (Multiuser Internet Mail Extensions) with this code. And confirm your desired type. You can also detect png, gif with this code.
if($_FILES["fname"]["type"] == "image/jpeg") { echo "File type is JPEG"; } I believe the following works:
Also note:
(exif_imagetype ($ ImagePathAndName) == IMAGETYPE_JPEG)
only reads the first few bytes looking for the image title, so it’s actually not enough to confirm that the image is damaged.
Below I use it in the logical expression "and", that is, both of these tests must be passed in order for the image to qualify as valid and not damaged, etc.:
if ((exif_imagetype($ImagePathAndName) == IMAGETYPE_JPEG) && (imagecreatefromjpeg( $ImagePathAndName ) !== false )) { echo 'The picture is a valid jpg<br>'; } Note. You should put this line of code at the top of the php code to avoid viewing warning messages from imagecreatefromjpeg ($ ImagePathAndName) when it encounters a fake / corrupted image file.
ini_set('gd.jpeg_ignore_warning', 1); When using $_FILES you rely on information sent by the client, which is not the best thing to do (you saw that this is not always the same thing, and if I remember correctly, $_FILES['...']['type'] can be faked).
If you are using PHP> = 5.3 (or you can install PECL packages), perhaps you can take a look at the Fileinfo extension. If you are using an older version, what about mime_content_type ?
And as Scott said, why only allow jpeg?
Looking back at the code is better: when you in the first case ( error > 0 ), do you assign the default file $imgData ? Why spaces around the "hyperlink"? And why do you always use the content-type to check, even if an error occurred on several lines before?
To finish, did you look at the manual ( File upload processing )?
Why don't you try creating an array of exceptions (the files you want the user to be able to load).
// Hyperlink for your website $hyperlink = "http://www.yourwebsitehere.com"; if($_FILES['fname']['error'] > 0) { $image= $hyperlink . "/holder.jpg"; } else { $image = $hyperlink . "/" . $_FILES['fname']['name']; } // Only accept files of jpeg format $exceptions = array("image/jpg", "image/jpeg", "image/pjpeg"); foreach($exceptions as $value) { if($_FILES['fname']['type'] != $value) { echo "I only accept jpeg images!"; break; // Or exit(); } }