Why is the below not recognizing that an image is being uploaded (.jpg)?
I am getting Uploaded file is not an image !!!
$finfo = finfo_open(FILEINFO_MIME_TYPE, 'C:\xampp\php\extras\magic\magic.mime');
if(strpos(finfo_file($finfo, $_FILES['userfile']['tmp_name']),"image")===0) {
// prepare the image for insertion
$imgData =addslashes (file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE (mysql_error());
// select the db
mysql_select_db ($db) OR DIE ("Unable to select db".mysql_error());
// our sql query
$sql = "INSERT INTO uploaded_images
(image, name)
VALUES
('{$imgData}', '{$_FILES['userfile']['name']}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg='<p>Image successfully saved in database with id ='. mysql_insert_id().' </p>';
}
else
$msg="<p>Uploaded file is not an image.</p>";
Detecting file types is surprisingly unreliable. Some of the simpler low-level file type detection programs just use the file extension to try and determine the type.
It’s better to use a tool that specifically works with images, such as
imagemagick, if you have the ability to install it on the server that’s running the code. Here’s an example that will tell you whether the file is actually a JPEG image without relying on the file name:However, if you don’t have access to install imagemagick you could use the GD library. Failing that, you will either have to trust that the file extension is correct or just trust that the file is an image.
On a separate note, it’s rarely a good idea to save images in the database, especially if they are then to be delivered as rendered images. MySQL is not designed to be efficient at that. It’s better to store them as files in a directory that can be publicly viewed. Having said that, I don’t know your application so you will be best placed to determine the best course of action.