Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check whether or not a file is an image?

Tags:

php

image

Can I check whether or not a certain file is an image? How can do this in PHP?

If the file is not an image, I want to give an alert message.

like image 776
pratik Avatar asked May 19 '12 06:05

pratik


People also ask

How can I tell what file type an image is?

If you are having trouble and want to check if you photo is a JPEG, look at the writing under the photo in its file name. If it ends . jpg or . jpeg- then the file is a JPEG and will upload.

How do you check if a file is a PNG?

Alternatively, open the suspected PNG in Notepad. If it's truly a PNG, it will have ‰PNG on the first line. Jpeg's will have JFIF somewhere near the start.


2 Answers

in PHP you can do it like following way

if ((($_FILES['profile_picture']['type'] == 'image/gif') || ($_FILES['profile_picture']['type'] == 'image/jpeg') || ($_FILES['profile_picture']['type'] == 'image/png')))

in Javascript You can do it like following way

function checkFile() {
   var filename = document.getElementById("upload_file").value;
   var ext = getExt(filename);
 //  alert(filename.files[0].filesize);
  // alert(ext);
   if(ext == "gif" || ext == "jpg" || ext=="png")
      return true;
   alert("Please upload .gif, .jpg and .png files only.");
   document.getElementById("upload_file").value='';
   return false;
}

function getExt(filename) {
   var dot_pos = filename.lastIndexOf(".");
   if(dot_pos == -1)
      return "";
   return filename.substr(dot_pos+1).toLowerCase();
}
like image 43
mack Avatar answered Nov 02 '22 13:11

mack


In addition to getimagesize(), you can use exif_imagetype()

exif_imagetype() reads the first bytes of an image and checks its signature.

When a correct signature is found, the appropriate constant value will be returned otherwise the return value is FALSE. The return value is the same value that getimagesize() returns in index 2 but exif_imagetype() is much faster.

For both functions, FALSE is returned if the file is not determined to be an image.

like image 180
Wesley Murch Avatar answered Nov 02 '22 13:11

Wesley Murch