Jump to content

for loop starting with 0001


Exoon

Recommended Posts

Hello, ive got lots of images i need to save so i decided to make a script to auto save them all to my hdd the only problem is the images are saved like

 

0001.jpg

0002.jpg

0003.jpg

 

etc etc...

 

i found this script on another site which i think might work but how can i get it to start from 0001 or is there a better way to do it?

 

<?php
for($number = 0001; $number < 0050; $number++)
{
$file = "www.mysite.com/boxart/$number.jpg";
$file_contents = file_get_contents($file);

$fh = fopen($file, "r");
$file_contents = ($file_contents);
fwrite($fh, $file_contents);
fclose($fh);
echo "got $number, moving to next image";
}
?>

 

Thanks in advance.

 

Link to comment
https://forums.phpfreaks.com/topic/85668-for-loop-starting-with-0001/
Share on other sites

I wrote a script for doing pretty much the same thing.

 

Sec, I'll see if I can dig it up.

 

function leading_zeros($value, $places)
{
    if (is_numeric($value)) {
        for ($x = 1; $x <= $places; $x++) {
            $ceiling = pow(10, $x);
            if ($value < $ceiling) {
                $zeros = $places - $x;
                for ($y = 1; $y <= $zeros; $y++) { $leading .= "0"; }
                $x = $places + 1;
            }
        }
        $output = $leading . $value;
    } else 
        $output = $value;
    return $output;
}

 

Usage is self explanatory.

 

<?php
for($number = 1; $number < 50; $number++)
{
$number = leading_zeros($number, 3);
$file = "http://www.mysite.com/boxart/{$number}.jpg";
$file_contents = file_get_contents($file);

$fh = fopen($file, "r");
$file_contents = ($file_contents);
fwrite($fh, $file_contents);
fclose($fh);
echo "got $number, moving to next image";
}
?>

 

Remember, PHP will think of any leading 0s as irrelevant and will use the number "0001" as "1" for example.

<?php
for ($i=1; $i <=10; $i++)
{
    $filename = sprintf('%04d.jpg', $i);
    echo $filename, '<br/>';
}
?>
-->
0001.jpg
0002.jpg
0003.jpg
0004.jpg
0005.jpg
0006.jpg
0007.jpg
0008.jpg
0009.jpg
0010.jpg

Wow, again your solution amazes me. So simple... looks like I'm updating my script!

try

<?php
for($number = 1; $number <= 50; $number++)
{
$file = sprintf('%04d.jpg', $i);
$file_contents = file_get_contents("http://www.mysite.com/boxart/$file");

$fh = fopen("my/hdd/path/$file", "w");                              // open in write mode (needs write permission)
fwrite($fh, $file_contents);
fclose($fh);
echo "got $file, moving to next image<br/>";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.