Q:

File rename through php

I have the code for file rename;
    <?php
$directory= 'J:\xampp\htdocs\rename\abc';
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
      rename($directory."/".$file, $directory."/".$index.".JPG");
        $index++;
    }

}
closedir($handler);
?>

Instead of renaming file as 1,2,3,4,....22
it renames the files as
1,10,11,12,13,14,15,.......
Any answer would be welcomed 

A:

Your code seems correct, as stated in the comment it might be a sorting  problem. To prevent this I usually "pad" my number with leading zero : 

01.JPG
02.JPG 
...
10.JPG

I use str_pad : 
$index = str_pad($index, 2, '0', STR_PAD_LEFT);

Your code would look like this : 
$directory= 'J:\xampp\htdocs\rename\abc';
$handler = opendir($directory);
$index = 1;
while ($file = readdir($handler)) {
    if ($file != "." && $file != "..") {
        $index = str_pad($index, 2, '0', STR_PAD_LEFT);
        rename($directory . "/" . $file, $directory . "/" . $index . ".JPG");
        $index++;
    }

}
closedir($handler);

I you have less than a hundred file you should pad with 1 zero, less than a thousand pad with 2 zeros and so on.
Hope this helps

