Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the image type in php [duplicate]

Tags:

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);
    fclose($fp);

    $update = mysql_query("UPDATE avatar SET image1='$data',type='$fileType' WHERE username='$user'",$this->connect);
} else {
    echo "<form enctype='multipart/form-data' action='http://www.example.com/cp/avatar' 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>
        </form>";
}
like image 735
user892134 Avatar asked Oct 28 '11 06:10

user892134


People also ask

How can I get image type in PHP?

The imagetypes() function is an inbuilt function in PHP which is used to return the image types supported by the PHP inbuilt installed library.

What is the type of image in PHP?

You can use the image functions in PHP to get the size of JPEG , GIF , PNG , SWF , TIFF and JPEG2000 images. With the exif extension, you are able to work with information stored in headers of JPEG and TIFF images.

How check file is image or not in PHP?

exif_imagetype() reads the first bytes of an image and checks its signature. exif_imagetype() can be used to avoid calls to other exif functions with unsupported file types or in conjunction with $_SERVER['HTTP_ACCEPT'] to check whether or not the viewer is able to see a specific image in the browser.


1 Answers

use getimagesize() or exif_imagetype()

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

and

$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.

like image 183
Peter Avatar answered Nov 03 '22 01:11

Peter