I am in the process of writing an image upload script. I am adding lots of things e.g. store outside webroot and access through php script etc. One thing I have read to check is that a file is uploaded instead of an image. E.g. stop myimage.php.jpeg
I have written the following code to check it is an image file. Is this the best way to check this file has an image name?
$imagename= $_FILES['myimage']['name'];
//check there is only one fullstop in the imagename
if (substr_count($imagename,".")===1){
$imagesuffix = substr($imagename, strpos($imagename, ".") + 1);
//if image type is not a particular type of image
if($imagesuffix != "jpg"|| $imagesuffix != "png"||$imagesuffix != "jpeg"||$imagesuffix != "gif"){
echo"image filename is valid";
}
else{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else{
echo"this filename is invalid";
}
If your concern is to only allow uploads of files that are images, then you'll have to look at the file contents.
<?php
$image = 'image_file_to_test.png';
if (($imageInfo = getimagesize($image, $jpegInfo)) === FALSE)
die('Not an image.');
// OR
if (($imageType = exif_imagetype($image)) === FALSE)
die('Not an image');
If so desired, you can inspect either $imageInfo
(docs) or $imageType
(docs) to determine the image format. Please note that exif_imagetype()
is the faster of the two, but it won't tell you as much as getimagesize()
.