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?
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: