Search code examples
phpwindowscommand-linefilenames

Sequentially number files by being prompted for the first number in php


php, command line, windows.

I need to sequentially number each .txt file in a directory. Any way I can specify the first number to use in the sequence in the command line when I type the script? (Instead of every time manually editing the script itself).

Or instead (even better) being prompted to enter the first number twice (for confirmation)?

Like, in command line ("285603" is just an example number):

c:\a\b\currentworkingdir>php c:\scripts\number.php 285603

or (even better)

c:\a\b\currentworkingdir>php c:\scripts\number.php
c:\a\b\currentworkingdir>Enter first number: 
c:\a\b\currentworkingdir>Re-enter first number: 

The numbering script:

<?php
$dir = opendir('.');
// i want to enter this number OR being prompted for it to enter twice in the command line 
$i = 285603;
while (false !== ($file = readdir($dir)))
{
    if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'txt')
    { 
        $newName = $i . '.txt';
        rename($file, $newName);
        $i++;
    }
}
closedir($dir);
?>

Any hints please?


Solution

  • You should use $argv variable. It is an array with a first element indicating script file name and next elements are arguments passed. Given you type php script.php 1234 in the console, $argv variable is as follows:

    array(4) {
      [0]=>
      string(10) "script.php"
      [1]=>
      string(4) "1234"
    }
    

    EDIT: Your code should be like below:

    <?php
    # CONFIRMATION
    echo 'Are you sure you want to do this [y/N]';
    $confirmation = trim(fgets( STDIN));
    if ($confirmation !== 'y') {
       exit (0);
    }
    
    $dir = opendir('.');
    $i = $argv[1];
    while (false !== ($file = readdir($dir)))
    {
        if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == 'txt')
        { 
            $newName = $i . '.txt';
            rename($file, $newName);
            $i++;
        }
    }
    closedir($dir);
    ?>