如果图像存在,请从URL下载图像

时间:2013-03-19 13:15:47

标签: php

我有这个网址www.example.com/1.png。我想运行一个循环,如下:

for ($i=0; $i<=10; $i++){
$url = 'www.example.com/'.$i.'.png';
}

现在我有10个网址。让我们说10个网址中有7个是图像,其他3个不可用。我想从每个网址下载图片,如果网址不存在则不会下载任何内容。

Heres同样的事情,但我认为更基本的解释:

www.example.com/1.png --- url exists, so i download the image and save it in my folder.
www.example.com/2.png --- url exists, so i download the image and save it in my folder.
www.example.com/3.png --- url doesnt exist, so i dont download anything
www.example.com/4.png --- url exists, so i download the image and save it in my folder.
www.example.com/5.png --- url exists, so i download the image and save it in my folder.
www.example.com/6.png --- url exists, so i download the image and save it in my folder.
www.example.com/7.png --- url doesnt exist, so i dont download anything
www.example.com/8.png --- url exists, so i download the image and save it in my folder.
www.example.com/9.png --- url exists, so i download the image and save it in my folder.
www.example.com/10.png  --- url doesnt exist, so i dont download anything

抱歉英语不好,有什么建议我可以解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

使用file_get_contents()下载图像会生成$http_response_header变量,其中包含您可以检查的HTTP响应标头。见documentation here

答案 1 :(得分:0)

您可以检查标头是否有404错误。

$file_headers = @get_headers($url);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
    //Does not exist
}
else
{
    //Exists, so put download code here
}

答案 2 :(得分:0)

你可以做的是在一个多卷曲请求中将它们全部排队,然后过滤掉那些不返回值的文件&lt; 399.通过这种方式你可以让curl一次性请求它们而不是一次一个。同时设置此操作应花费的时间,例如5秒。

相关问题