Search code examples
phpimagefile-type

How to test file-type of URL in PHP?


I'm trying to download an image from a URL, and if it's a gif, I'm going to convert it, and otherwise, I'm going to just leave it as it is. However, much like this question (it's actually to solve the same problem), I have URLs that don't contain file extensions, so I need to somehow determine the file-type another way.

What's the best way to do this? Using headers would probably be easy, but since I know the URL will have to involve a redirect before I can actually access the file, I'm not sure the best way to test it?


Solution

  • Just send a request to the URL, follow any returned redirects (your HTTP client should do that for you), then read the Content-Type header.
    Note that the header cannot be trusted; a malicious server or proxy can set any header it wants.