开发者

How to find the extension of an image from path in PHP?

Is there any standard function in PHP to find only extension of an image from the corresponding file path?

For example ff my image path is like '/testdir/dir2/im开发者_StackOverflow社区age.gif' then the function should return 'gif'.

Thanks


$ext = pathinfo(
    parse_url('/testdir/dir2/image.gif?foo=bar', PHP_URL_PATH), 
    PATHINFO_EXTENSION
); //$ext will be gif


It's usually more desirable to detect the actual image type (not by extension but by its contents). For that, use getimagesize().


I had problem with first answer and url with anchor ex. google.com/image.jpg#anchor

better solution

$filename_from_url = parse_url($url);
$ext = pathinfo($filename_from_url['path'], PATHINFO_EXTENSION);


I think the most correct way is using echo exif_imagetype function:

   exif_imagetype("/testdir/dir2/image.gif");

   function get_image_type($image_path){

        $extension  = array(IMAGETYPE_GIF => "gif",
        IMAGETYPE_JPEG => "jpeg",
        IMAGETYPE_PNG => "png",
        IMAGETYPE_SWF => "swf",
        IMAGETYPE_PSD => "psd",
        IMAGETYPE_BMP => "bmp",
        IMAGETYPE_TIFF_II => "tiff",
        IMAGETYPE_TIFF_MM => "tiff",
        IMAGETYPE_JPC => "jpc",
        IMAGETYPE_JP2 => "jp2",
        IMAGETYPE_JPX => "jpx",
        IMAGETYPE_JB2 => "jb2",
        IMAGETYPE_SWC => "swc",
        IMAGETYPE_IFF => "iff",
        IMAGETYPE_WBMP => "wbmp",
        IMAGETYPE_XBM => "xbm",
        IMAGETYPE_ICO => "ico");

        return $extension[exif_imagetype($image_path)];
}


As Col. Shrapnel mentioned; there's quite a few ways

$path = '/some/where/img.gif';
$path = explode('.',$path);
$path = end($path);


I think the easy way using strrpos() and substr() methods

$path = "/testdir/dir2/image.gif";
$ext = substr($path, strrpos($path, '.')+1);
echo $ext; // output will be gif

more answers for Another Question related to this Question


I would recommend you to run any uploaded/linked image(s) through a GD/ImageMagick check and re-save it to prevent any malicious codes hidden within the images. This would also allow you to save all of the images with the same extension to make things easier for you.

http://www.php.net/imagepng
http://www.php.net/imagegif
http://www.php.net/imagejpeg


I would recommend you perfect way

$file_path = '/some/where/img.gif';  
$info = new SplFileInfo($file_path);  
$file_extension = $info->getExtension(); 
var_dump($file_extension);

for more detail here The SplFileInfo class

I hope this will help you.

Cheers!

Mudassar Ali


Basic string functions, strrpos() and substr() can do that for you. As well as many other fancy ways.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜