Edgar
Edgar

Reputation: 1131

Download image from url if image exists

I have this url www.example.com/1.png. I want to run a loop, like so:

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

Now i have 10x urls. Lets say 7 out of 10 urls are images, and the other 3 are not available. I want to download image from each o urls, and if the url doesnt exists then it wouldnt download anything.

Heres the same thing but explained more basicly i think:

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

Sorry for bad english, any suggestions how i can solve this problem?

Upvotes: 0

Views: 348

Answers (3)

Mike Q
Mike Q

Reputation: 7327

What you could have done is queued them all up in one multi curl request and then filter out the ones that don't return back a value < 399. That way you could have curl requested them all at once instead of one at a time. Also set a time out for the amount of time this operation should take, say 5 seconds.

Upvotes: 0

Corneliu
Corneliu

Reputation: 1110

Downloading the images with file_get_contents() would generate a $http_response_header variable, which contains the HTTP response headers which you can check. See documentation here

Upvotes: 1

loler
loler

Reputation: 2587

You can check headers for 404 error.

$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
}

Upvotes: 0

Related Questions