Saving images php code
I'm trying to save images from a url.
<?php
$numb开发者_如何学Pythoner = 200;
while ($number <= 1000){
$url = 'http://site.com/productphotos/gallery_'.$number.'-l.jpg';
$img = ''.$number.'.jpg';
file_put_contents($img, file_get_contents($url));
}
$number++;
?>
so there is site.com/productphotos/gallery200-100-l.jpg
why isnt this working?
It seems that you increment your $number after closing your while() {} function ...
Aside from the fact your URL format does not match that of the example given (as in Alex's answer), your loop will execute infinitely ($number
vs $num
).
Try this loop instead
for ($number = 200; $number <= 1000; $number++)
Edit: At least, it did before you edited the question ;-)
Edit #2: Syntax errors aside, I don't see PHP being the optimal solution for this "problem". You could easily write a shell / batch script using wget
to fetch the images.
#!/bin/bash
for i in {200..1000}; do
wget "http://example.com/gallery/${i}.jpg"
done
The string being made looks like this on each iteration...
http://site.com/productphotos/gallery_200-l.jpg
...which does not match what you quoted...
http://site.com/productphotos/gallery200-100-l.jpg
It could also be because you have allow_url_fopen()
off. If you can't change it and it's off, use a library such as cURL to get the image.
Also, you are making 800 requests from that loop, which is quite an amount. You can give PHP a breather by using sleep(1)
in that loop and making sure the script doesn't time out with set_time_limit(0)
. Of course this won't be fast enough to do in a end user initiated HTTP request, so try and run this process from a scheduler such as a Cron job.
If you really want a specific answer, tell me how it doesn't work - any errors, is the image saved but wrong, etc.
精彩评论