Reputation: 1233
I am stuck on this, hoping somebody has an idea.
I am trying to determine the file extension of a remote dynamic image path.
https://d2sh4fq2xsdeg9.cloudfront.net/contentAsset/image/93e9fb86-8f30-4fea-bdb9-90d63eb67e44/image/byInode/1/filter/Resize,Jpeg/jpeg_q/70/resize_w/1000
or, say, https://placekitten.com/g/1000/1000
I have tried using parse_url
and finfo_file
as well as SplFileInfo
but none of those worked in my testing of them. Maybe something in one of them I do not know about(?).
I thought about using file_get_contents
-> file_put_contents
and saving it locally, but that would not work without knowing the file extension, which is the root cause of all of this to begin with.
I cannot convert it into an image data:
(base64) because that requires knowing the mime type, and that is not possible, as far as I know, without, again, knowing the file extension and/or saving it locally.
And, one cannot just assume that it is always going to be a xyz-file type.
And, doing some type of preg_match just seems like the worse way to go about this, as different developers/programs uses different methods for this kind of dynamic image resizing techniques.
I suppose I could always do a strpos($haystack, $needle)
checking for a combination of needles (gif,png,jpeg,etc) but, well, uggggghhh to that idea, eh.
So, just thought that I would post here and see if anybody has any good idea on how to go about getting the extension from dynamic image uri's.
Upvotes: 0
Views: 709
Reputation: 17805
Well, you can make a cURL request and check the content_type
of the response header.
<?php
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://d2sh4fq2xsdeg9.cloudfront.net/contentAsset/image/93e9fb86-8f30-4fea-bdb9-90d63eb67e44/image/byInode/1/filter/Resize,Jpeg/jpeg_q/70/resize_w/1000");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$result = curl_exec($ch);
echo curl_getinfo($ch)['content_type'];
curl_close($ch);
Output:
image/jpeg
#Update:
If all you want to do is to just check the image extension and not want image file in return, then you can just make a HEAD request as mentioned by @SalmanA in the comments.
You need to add the following line to above curl request:
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"HEAD");
Upvotes: 3
Reputation: 279
First take the mime-type of the image using finfo.
$url = "https://d2sh4fq2xsdeg9.cloudfront.net/contentAsset/image/93e9fb86-8f30-4fea-bdb9-90d63eb67e44/image/byInode/1/filter/Resize,Jpeg/jpeg_q/70/resize_w/1000";
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->buffer(file_get_contents($url));
print_r($type);
then get file extension using below
function getExtension ($mime_type){
$extensions = array('image/jpeg' => 'jpeg',
'text/xml' => 'xml');
// Add as many other Mime Types / File Extensions as you like
return $extensions[$mime_type];
}
Upvotes: 2
Reputation: 677
You can try:
$url = 'https://placekitten.com/g/1000/1000';
$type = get_headers($url, 1)["Content-Type"];
echo $type;
Upvotes: 0