Oto Shavadze
Oto Shavadze

Reputation: 42753

Get image extension

I want get uploaded image extension.

As I know, best way is getimagesize() function.

but this function's mime, returns image/jpeg when image has .jpg or also .JPEG extension.

How can get exactly extension?

Upvotes: 14

Views: 53693

Answers (9)

James
James

Reputation: 135

$file_ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);

or to make it clean

$filename= $_FILES["file"]["name"];
$file_ext = pathinfo($filename,PATHINFO_EXTENSION);

Upvotes: 1

eozzy
eozzy

Reputation: 68650

$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];

Upvotes: 0

49volro
49volro

Reputation: 1165

For those who want to check if image type is JPEG, PNG or etc. You can use exif_imagetype function. This function reads the first bytes of an image and checks its signature. Here is a simple example from php.net:

<?php
if (exif_imagetype('image.gif') != IMAGETYPE_GIF) {
   echo 'The picture is not a gif';
}
?>

Upvotes: 0

vasudev
vasudev

Reputation: 410

You can also use strrpos and substr functions to get extension of any file

$filePath="images/ajax-loader.gif";

$type=substr($filePath,strrpos($filePath,'.')+1);

echo "file type=".$type;

output: gif

if you want extension like .gif

$type=substr($filePath,strrpos($filePath,'.')+0);

output: .gif

Upvotes: 6

Siki
Siki

Reputation: 111

You can also explode the file name with dots and take the end of the array as follows:

$ext = end(explode('.', 'image.name.gif'));

According to: Two different ways to find file extension in PHP

And a new way for you lol:

$ext = explode('.', 'file.name.lol.lolz.jpg');
echo $ext[count($ext) - 1];

Upvotes: 0

Devang Rathod
Devang Rathod

Reputation: 6736

$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);

Upvotes: 4

dfsq
dfsq

Reputation: 193261

One more way to do it:

$ext = strrchr($filename, "."); // .jpg

Upvotes: 3

lupatus
lupatus

Reputation: 4248

you can use image_type_to_extension function with image type returned by getimagesize:

$info = getimagesize($path);
$extension = image_type_to_extension($info[2]);

Upvotes: 33

phpalix
phpalix

Reputation: 689

$ext = pathinfo($filename, PATHINFO_EXTENSION);

Upvotes: 34

Related Questions