0

I a have a code to upload images to my server however before uploading the image the code checks whether the uploaded file is an image by checking its extension (allowed extensions are "jpg", "png" and "gif"), however I just realized that this isn't secure enough because I could easily create a "file.php" and rename it "file.png" and then the code wouldn't prevent file to be uploaded. Is there an alternative way to detect weather the file is an image?

UPDATE: I am using $_FILES to get the images.

1
  • There is no 100% reliable way; just don't execute .png files with php (or: only execute code you 100% trust). Aug 9, 2014 at 10:01

3 Answers 3

0

well, you can do this:

$image = "myImage.jpg";// the path to the file name

$res = getimagesize($image);

if($res === true)
{
 // this is an image
}

getimagesize() is a function to get info of an image. If the given filename is not an image, then it returns false, else it returns an array of image's info such as width and height.

If you want to check the image which is in $_FILES super array, then the following code should be used:

getimagesize($_FILES['file']['tmp_name'])

I assume your file input is named "file"

7
  • When used this function getimagesize($_Files["name"]"tmp_name") I get Warning: getimagesize(1): failed to open stream: No such file or directory in index.php on line 40 Aug 9, 2014 at 6:12
  • because the address you pass to the function is incorrect. It has nothing to do with the function, the URL to the file is not correct so that PHP cannot find the image and throws an error. Aug 9, 2014 at 6:15
  • what is the correct url then for $_FILES Aug 9, 2014 at 6:22
  • wait to update the answer Aug 9, 2014 at 6:24
  • The code works but when I created a jpg file with text "dsvsd" or "" I get error getimagesize(): Read error! Aug 9, 2014 at 6:43
0

You can also check like this $_FILES['file_upload']['type']

Example:

 if($_FILES['file_upload']['type'] != 'image/png'){
       //message to inform the user
 }
1
  • 1
    I think that's coming from the browser though.
    – DanMan
    Aug 9, 2014 at 6:59
0

You may simply use getimagesize().

It returns zeros for sizes on non-images.

Not the answer you're looking for? Browse other questions tagged or ask your own question.