0

我知道我可以使用以下方法保存图像:

$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));

但是如果我不知道下载图像的格式怎么办?如果它是“png”怎么办?在保存之前如何确定目标图像的类型?

4

1 回答 1

1

最好的办法就是下载它并稍后重命名文件。这样,您只需提出一个请求。

但是,您可以做的另一件事是发出 HTTP HEAD 请求。这将获取所有响应标头,包括Content-Type标头,因此您可以在下载文件之前决定是否需要该数据。但是,并非所有服务器都支持 HEAD 请求。

无论如何,cURL 是最简单的方法:

$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);
于 2014-12-06T15:28:19.247 回答