Reputation: 42753
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
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
Reputation: 68650
$size = getimagesize($filename);
$ext = explode('/', $size['mime'])[1];
Upvotes: 0
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
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
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
Reputation: 6736
$image = explode(".","test.file.hhh.kkk.jpg");
echo end($image);
Upvotes: 4
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