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.
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.
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.
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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With