# Renaming files in ascending order w/ PHP. How?

**URL:** <https://forum.kirupa.com/t/renaming-files-in-ascending-order-w-php-how/192501>\
**Category:** Uncategorized\
**Created:** [June 29, 2006, 12:26am UTC](https://forum.kirupa.com/t/renaming-files-in-ascending-order-w-php-how/192501 "2006-06-29T00:26:03Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![jpearson311](https://avatars.discourse-cdn.com/v4/letter/j/977dab/32.png) [@jpearson311](https://forum.kirupa.com/u/jpearson311)\
**Post date:** [June 29, 2006, 12:26am UTC](https://forum.kirupa.com/t/renaming-files-in-ascending-order-w-php-how/192501/1 "2006-06-29T00:26:03Z")

</div>

I’m in need of renaming a bunch of images in a directory and am stuck on how to do it. I created a file that I can go to and put in the directory and what I’d like the file name to begin with, but I’d like to rename the files in a numbered fashion in ascending order (i.e., 1.jpg, 2.jpg, 3.jpg, etc.).

I need the images to stay in the appropriate directories so the names have to be different and readable on a unix platform. Right now they’re not. Here is what I have:

\<?  
if (isset($submit) && $file\_name) {

```
    $directory = $file_directory;
    
    $file_name = stripslashes($file_name);
    $directory = str_replace("\\\\", "/", $directory);
    $directory = stripslashes($directory);
        
         $openfile = opendir($directory);

```

while($oldfile[] = readdir($openfile)) ;  
closedir($openfile);

foreach ($oldfile as $file){

if ($file=="." or $file=="…" or is\_dir($file)) continue;

$new\_name = $file\_name . “-” . $file;

$dir1 = $directory . “/” . $file;  
$dir2 = $directory . “/” . $new\_name;

rename($dir1, $dir2);

echo $new\_name . "- | - ";  
echo $dir1;  
echo “\<br\>\<br\>”;  
echo $dir2;  
echo " | | " . $count . " - " . $numfiles;  
echo “\<Br\>\<br\>\<br\>\<br\>”;

```
            }
            
            ?&gt;
            &lt;META HTTP-EQUIV="refresh" content="15;URL=index.php"&gt;
            &lt;?
            
            closedir($openfile);

```

} else {  
?\>

\<form method=“post”\>  
Directory:\<br\>  
\<input type=“text” name=“file\_directory” size=“40” style=“border-width: 1px; border-style: solid; font-size: 10px;”\>\<br\>  
\<br\>  
Name to put in front:\<br\>  
\<input type=“text” name=“file\_name” size=“40” style=“border-width: 1px; border-style: solid; font-size: 10px;”\>\<br\>  
\<br\>  
\<input type=“submit” name=“submit” value=“Submit” style=“border-width: 1px; border-style: solid; font-size: 10px;”\>  
\</form\>  
\<?  
}  
?\>

Any help would be greatly appreciated. Thanks. 🙂

JP311
