4

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?

Community
  • 1
  • 1
404 Not Found
  • 3,635
  • 2
  • 28
  • 34
  • you could try the fileinfo pcl extension maybe? http://www.php.net/manual/en/ref.fileinfo.php – Ben Jun 29 '12 at 03:03
  • I think you want [`finfo_file()`](http://www.php.net/manual/en/function.finfo-file.php). – Jared Farrish Jun 29 '12 at 03:03
  • 1
    I tried to use finfo_file, but it throws an error "Failed identify data 0:(null)" when I use a full url as the filename. – 404 Not Found Jun 29 '12 at 03:14
  • Why are you wanting to know before it gets to your server? Get it, store it temporarily or whatnot, figure out if it's `gif` or not, convert if necessary, and be done with it. You're going to get the file anyways, right? – Jared Farrish Jun 29 '12 at 03:19
  • The way I see it is, from an efficiency standpoint, downloading every file to test isn't very good when only a few are going to need to be converted. – 404 Not Found Jun 29 '12 at 03:21

1 Answers1

1

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.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964