How do I make it so if the filetype is not a JPG, do not upload Also, how do I deal with them uploading fake JPG's like .exe's renamed to .jpg?
there is one way using $_FILES['userfile']['type'] Which gives he mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted ..... second option is using GD library but for the methods to work you may need to upload the file in some temp directory and then apply GD functions to determine file contents and types.
list($width, $height, $type) = getimagesize($_FILES['tmp_name']); if ($type == IMAGETYPE_JPEG) { // it's a JPEG } else { // not a JPEG } PHP:
Prolly not the cleanest thing out there, but it works $imagename = $_FILES['photo']['name']; $imagetype = $_FILES['photo']['type']; $imagefilesize = $_FILES['photo']['size']; $imagetmp = $_FILES['photo']['tmp_name']; $imagesize = getimagesize($imagetmp);//references path which imagetmp has $validtypes= "jpeg|jpg|gif"; if(!preg_match("/$validtypes/i", $imagetype)) { $photoerror = "The file you attempted to upload is not a valid format. Please try again.\n"; } elseif(move_uploaded_file($imagetmp, "$_SERVER[DOCUMENT_ROOT]/photos/$imagename")) { $dbHost = "localhost"; $dbName = ""; $dbTable = ""; $dbUser = ""; $dbPass = ""; $dbHandle = mysql_connect($dbHost,$dbUser,$dbPass) or die(mysql_error()); mysql_select_db($dbName) or die(mysql_error()); mysql_query("UPDATE $dbTable SET `PHOTO` = '1' WHERE `ID` = '$id'"); mysql_close($connection); $photoerror = "File is valid, and was successfully uploaded.\n"; } else { $photoerror = "There was an error with the upload. Please try again.\n"; } PHP:
Yeah, except there is a bunch of extra mysql stuff he didn't ask for, and unless you use getimagetype() they will be able to upload, say, a GIF, and rename it to a .JPG, and it will still be a gif.
Make sure when validating the mime file types you use jpeg and pjpeg, Firefox uses jpeg while IE uses pjpeg.. That gave me a headache for a while
Try this code block. U may get help :0 $sPhotoFileName = $_FILES['photo']['name']; // get client side file name if ($sPhotoFileName) // file uploaded { $aFileNameParts = explode(".", $sPhotoFileName); $sFileExtension = end($aFileNameParts); // part behind last dot if ($sFileExtension != "jpg" && $sFileExtension != "JPEG" && $sFileExtension != "JPG") { die ("Choose a JPG for the photo"); } }
Again, that is bad advice and will allow someone to rename an EXE to a JPG, and upload a JPG. The ONLY way to do it is to crack open the file using getimagesize() to see if the file is really a JPG. Mime type is useless, checking the filename is useless because they can just rename it.
So, renaming an EXE to a JPG will even get past a mime type? I was under the impression that mime types were a bit more complex and harder to crack then simply changing the file extension.... Thanks for the info Robert..