Automatic image format detection in PHP

I am looking for a way to take a user uploaded image that is currently put in a temporary location ex: /tmp/jkhjkh78 and create a php image from it, autodetecting the format.

Is there a more clever way to do this than a bunch of try/catching with imagefromjpeg, imagefrompng, etc?


Solution 1:

This is one of the functions of getimagesize. They probably should have called it "getimageinfo", but that's PHP for you.

Solution 2:

   //Image Processing
    $cover = $_FILES['cover']['name'];
    $cover_tmp_name = $_FILES['cover']['tmp_name'];
    $cover_img_path = '/images/';
    $type = exif_imagetype($cover_tmp_name);

if ($type == (IMAGETYPE_PNG || IMAGETYPE_JPEG || IMAGETYPE_GIF || IMAGETYPE_BMP)) {
        $cover_pre_name = md5($cover);  //Just to make a image name random and cool :D
/**
 * @description : possible exif_imagetype() return values in $type
 * 1 - gif image
 * 2 - jpg image
 * 3 - png image
 * 6 - bmp image
 */
        switch ($type) {    #There are more type you can choose. Take a look in php manual -> http://www.php.net/manual/en/function.exif-imagetype.php
            case '1' :
                $cover_format = 'gif';
                break;
            case '2' :
                $cover_format = 'jpg';
                break;
            case '3' :
                $cover_format = 'png';
                break;
            case '6' :
                $cover_format = 'bmp';
                break;

            default :
                die('There is an error processing the image -> please try again with a new image');
                break;
        }
    $cover_name = $cover_pre_name . '.' . $cover_format;
      //Checks whether the uploaded file exist or not
            if (file_exists($cover_img_path . $cover_name)) {
                $extra = 1;
                while (file_exists($cover_img_path . $cover_name)) {
        $cover_name = md5($cover) . $extra . '.' . $cover_format;
                    $extra++;
                }
            }
     //Image Processing Ends

this will make image name look cool and unique

Solution 3:

Use exif_imagetype() if it's available ..:

http://www.php.net/manual/en/function.exif-imagetype.php

I'm pretty sure exif functions are available by default (i.e. you have to specifically exclude them rather than specifically include them) when you install php

Solution 4:

You could try finfo_file(), apparently an improved version of mime_content_type().

Edit: OK, getimagesize() is better..