3 ms·
PHP coding question
To all PHP hackers out there,
I have a basic PHP question. The application I am working on currently allows a user to upload a jpeg or gif image only. My code for enforcing this rule is as follows:
if($type!="image/gif" || $type!="image/jpeg"){
$error = "Your image needs to have a gif or jpeg format";
}
$type in this case is obtained from $_FILES['file']['type']
However, this does not seem to work. Non-JPEG images get rejected properly. However even JPEG images are rejected. Any ideas on how I can check the type of the image.
- prime2 18y agotry: ($type!="image/gif" || $type!="image/jpeg" || $type!="image/jpg" || $type!="image/prjpeg")
- symbiotic 18y agoAn easy way to debug is to just echo $type for a file that you want to allow and see what it is :)
- noodle 18y agoconsider using the getimagesize function. http://us.php.net/getimagesize http://us.php.net/getimagesize the comments have some useful info on how to get the image type. iirc, the problem using the file type string is that its not consistent.
- deleted 18y ago[deleted]
- pmorici 18y agoUmmm, that statement is always going to be true. This isn't a PHP question this is a basic logic question. You really want... if (!(type == gif or type == jpeg)) { error } or change your 'or' to an 'and' ie: if (type!=gif and type!=jpeg) { error } http://en.wikipedia.org/wiki/De_Morgan's_laws http://en.wikipedia.org/wiki/De_Morgan's_laws
- streblo 18y agoSo, what you're saying is, if the type isn't a gif OR if it isn't a jpeg, reject. The problem is that every picture isn't a gif or isn't a jpeg. jpeg images will be rejected because they aren't gifs, and gifs will be rejected because they aren't jpegs. You need to do what pmorici said and change this to an 'and' statement, or negate the entire statement you already have.
- technoguyrob 18y agoThis isn't the only problem. Not all gifs and jpegs use that MIME [1]. Try this: $allowed_image_types = array('image/gif', 'image/x-gif', 'image/pjpeg', 'image/jpeg', 'image/x-pjpeg', 'image/x-jpeg', 'image/x-jpg', 'image/jpg'); if (!in_array($type, $allowed_image_types)) { $error = 'ERROR: You can only upload GIF and JPG files.'; } [1] http://www.webmaster-toolkit.com/mime-types.shtml http://www.webmaster-toolkit.com/mime-types.shtml
- whalesalad 18y agoThis is the best method right here, hands down.