Thursday 14 July 2016

PHP Function to check whether a file is an image

Easy and efficient way to check whether a file is a image file or not. Use the following function to determine whether a file is a image type or not.

function checkFileForImage($image_path) {
    $image_info = getimagesize($image_path);
    $image_type = $image_info[2];
   
    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP))) {
        // Following file types can also be added in above array if needed
        // IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_JPEG2000, IMAGETYPE_XBM, IMAGETYPE_ICO, IMAGETYPE_UNKNOWN, IMAGETYPE_COUNT

        $image_width = $image_info[0]; // Additional feature to get width
        $image_height = $image_info[1]; // Additional feature to get height
        return true;
    }
    return false;
}


In the above function "getimagesize" function does the trick. It returns the array containing the details like width, height and image type. Function "checkFileForImage" returns true if the $image_path is an image and false if not.

No comments:

Post a Comment