How to figure out type of the image before downloading it?

151 Views Asked by At

I know I can save an image using the following method:

$input = 'http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com';
$output = 'google.com.jpg'; // << How to save the image with proper extension?
file_put_contents($output, file_get_contents($input));

But what if I don't know the format of the downloaded image? What if it's "png"? How can I figure out the type of target image before saving it?

1

There are 1 best solutions below

2
On BEST ANSWER

The best thing to do is just download it and rename the file later. That way, you only have to make one request.

Another thing you can do however is make an HTTP HEAD request. This gets all of the response headers, including the Content-Type header, so you can decide if you want that data or not before you download the file. However, not all servers support HEAD requests.

In any case, cURL is the easiest way to do this:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/something'); 
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$headers = curl_exec($ch);