After your help, many stackoverflow posts, the solution is at the bottom of this post as an UPDATE.
I am trying to save some images automatically using this code in a php file :
for ($num1=100;$num1<999;$num1++)
{
for ($num2=100;$num2<999;$num2++)
{
$postURL = "http://link_00000'.$num1.'_'.$num2.'.jpg";
$ch = curl_init('http://link_00000'.$num1.'_'.$num2.'.jpg');
$fp = fopen($postURL, '/path/Apolo/img/'.$num1.'_'.$num2.'.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}
}
First question :
$num1
and $num2
should start from 000 to 999 and not from 0 to 999. Putting more $num
variables ($num3
, $num4
...) would be a solution but I presume there is a better one for the digits.
Second question :
The images are not saved. I tried this one as well but it did not work:
copy($postURL, '/path/img/'.$num1.'_'.$num2.'.jpg');
Third question :
How can I prevent an action like d-dos attack? If I load the links without a time delay, probably the website will be down.
UPD:
for ($num1=000;$num1<999;$num1++)
{
for ($num2=000;$num2<999;$num2++)
{
$url = 'http://link.com/00000'.sprintf("%03d", $num1).'_'.sprintf("%03d", $num2).'.jpg';
echo ''.$num1.'_'.$num2.'';
echo "\n";
if (@getimagesize($url)) \\ checks if url-image exists
{
echo $url;
$ch = curl_init($url);
$fp = fopen('/path/Apolo/00000'.sprintf("%03d", $num1).'_'.sprintf("%03d", $num2).'.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
sleep(1); //1 second delay to avoid d-dos
}
}
}
When you are dealing with integers you cannot say 000, as that is equal to 0, if you want it to write 000, then you should use a string instead.
In your example you are looping through the numbers, so writing it as strings would be messy if you wan't to loop it.
Therefor the best solution would be to just add the leading 0's yourself, this can be done like this:
sprintf("%03d", $num1);
This will automatically add the leadings zeroes, that you wanted.
UPDATE 1: (forgot to answer the save image)
For saving the images you can do it like this:
file_put_contents('/path/Apolo/img/filename'.sprintf("%03d", $num1).'_'.sprintf("%03d", $num2).'.jpg', file_get_contents($postURL));
Update 2: (code example):
for ($num1=100;$num1<999;$num1++)
for ($num2=100;$num2<999;$num2++){
$postURL = 'http://link_00000'.sprintf("%03d", $num1).'_'.sprintf("%03d", $num2).'.jpg';
$path = '/path/Apolo/img/filename'.sprintf("%03d", $num1).'_'.sprintf("%03d", $num2).'.jpg';
file_put_contents($path, file_get_contents($postURL));
}
Question 3:
There at lots of ways to prevent DDOS attacks, but if you just wan't your site to run quickly and prevent/handle DDOS attacks then change your DNS to cloudflare, it's worth it and their free account is more then enough for you.