简体   繁体   中英

PHP get file extension from image url not ended in .ext

pathinfo() works fine only when the extension is present.

WORKS FINE:

$sourceUrl = "site.com/image.png";    
$photoExt = pathinfo($sourceUrl, PATHINFO_EXTENSION);

.

NOT WORKING

$sourceUrl = "www.gravatar.com/avatar/d9d3bffa0ca503c495b2461881688467?s=32&d=identicon&r=PG";    
$photoExt = pathinfo($sourceUrl, PATHINFO_EXTENSION);

I couldn't see solution on how to get file/image extension when the source doesn't ended on it's file type.

Any solution?

When you fetch the file look at the Content-Type header. It will be image/[something] .

That is the filetype and you can derive an extension from that.

You cannot use pathinfo to get extension of file without extension.

For this remote file we only know what's the content-type of this image ( Content-Type => image/jpeg ). But this content-type can have jpg or jpeg extension and we simple don't know what's this file real extension so PHP cannot determine it either.

If you want to simple check image type of this resource you can use:

echo exif_imagetype('http://www.gravatar.com/avatar/d9d3bffa0ca503c495b2461881688467?s=32&d=identicon&r=PG');

It will return 2, what is IMAGETYPE_JPEG according to documentation but still you won't know anything about real file extension.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM