How to get the image type in php

I am trying to get the image type in the database but the below isn’t working. How do I detect if the image is png, jpeg or gif?

if(isset($_POST['submit'])) {
    $fileType = $_FILES['image']['type'];
    $tmpname = $_FILES['image']['tmp_name'];
    $fp = fopen($tmpname,'r');
    $data = fread($fp,filesize($tmpname));
    $data = addslashes($data);

    $update = mysql_query("UPDATE avatar SET image1='$data',type='$fileType' WHERE username='$user'",$this->connect);
} else {
    echo "<form enctype='multipart/form-data' action='' method='post'>
        <div id='afield1' >Upload</div><div id='afield2'><input type='hidden' name='MAX_FILE_SIZE' value='102400' /><input type='file' size='25' name='image' /></div>
        <div id='asubmit'><input type='submit' name='submit' class='button' value='Save Changes' /></div>

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

use getimagesize() or exif_imagetype()

// integer - for example: IMAGETYPE_GIF, IMAGETYPE_JPEG etc.
$type   = exif_imagetype($_FILES['image']['tmp_name']);


$info   = getimagesize($_FILES['image']['tmp_name']);
$mime   = $info['mime']; // mime-type as string for ex. "image/jpeg" etc.
$width  = $info[0];      // width as integer for ex. 512
$height = $info[1];      // height as integer for ex. 384
$type   = $info[2];      // same as exif_imagetype

Mind that exif_imagetype is much faster than getimagesize. Check documentation for more info.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply