0

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?

B Faley
  • 17,120
  • 43
  • 133
  • 223

1 Answers1

1

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);
Brad
  • 159,648
  • 54
  • 349
  • 530
  • That's great, but what if the server does not support HEAD requests? – B Faley Dec 06 '14 at 15:38
  • @Meysam In that case you would have to perform a normal GET request and cancel the download. At that point though you could just inspect the response headers and get the type. What you should be doing is downloading the data first, and then renaming that file. – Brad Dec 06 '14 at 15:55