I get a random image like this:
https://picsum.photos/200/200?random=61081
How can I get the image extension? jpg/png etc.?
I’ve considered this: $extension = pathinfo($file, PATHINFO_EXTENSION);
but it does not work.
EDIT: $extension = pathinfo($file, PATHINFO_EXTENSION);
gives an empty string.
4
Answers
The link is just a generated path, not the actual file path. In such cases, the response should include the type of the received content, such as JSON, image, etc.
You can read this using the
get_headers()
function.More information
get_headers()
– PHP Docs (with example output, where can foundContent-Type
)What is
Content-Type
– MDN Docs (this value is alwaysMIME type
)What is
MIME type
– MDN DocsList of MIME types – iana.org
How to get File-Extension from MIME-Type – StackOverflow Answer
You can try
That URL is a simple 302 redirect to the actual resource. You can find the extension of the resource by extracting the URL from the
location
header that you receive. This way you don’t have to download the picture to figure it out.Results in:
Since the extension is given in the redirection url, you can just parse it without downloading the whole image: