Sequentially Rename All Image Files In A Directory With PHP

2nd March 2009 - 2 minutes read time

The following function will rename all of the image files in a directory to be sequential. The parameters are the path of the directory that the files are in and the name of a function that will be used to sort the array of files through the PHP usort() function.

function sequentialImages($path, $sort=false) {
 $i = 1;
 $files = glob($path."/{*.gif,*.jpg,*.jpeg,*.png}",GLOB_BRACE|GLOB_NOSORT);
 
 if ( $sort !== false ) {
  usort($files, $sort);
 }
 
 $count = count($files);
 foreach ( $files as $file ) {
  $newname = str_pad($i, strlen($count)+1, '0', STR_PAD_LEFT);
  $ext = substr(strrchr($file, '.'), 1);
  $newname = $path.'/'.$newname.'.'.$ext;
  if ( $file != $newname ) {
   rename($file, $newname);  
  }
  $i++;
 }
}

The following function can be used in the second parameter to sort the files by their last modified time.

function sort_by_mtime($file1, $file2) {
 $time1 = filemtime($file1);
 $time2 = filemtime($file2);
 if ( $time1 == $time2 ) {
  return 0;
 }
 return ($time1 < $time2) ? 1 : -1;
}

Putting these two function together we can call the sequentialImages() function like this.

sequentialImages('files','sort_by_mtime');

This function takes the following set of images:

file1.gif
file2.gif
wibble.gif
wobble.gif
02.gif

And renames them to the following:

01.gif
02.gif
03.gif
04.gif
05.gif

 

Comments

Permalink
Good code! A personal preference would be to reverse the sorting by last modified so that the 001.gif is the oldest of the files, rather than having 001.gif as the newest. To do this, change the 6th line in the sort function to: return ($time1 < $time2) ? -1 : 1;

Jamie Bicknell (Wed, 03/04/2009 - 17:15)

Permalink
Hi, im interested to use your function whit file upload. I have this simple code, how can i do implements your function? my code"; if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) { echo "File is valid, and was successfully uploaded.\n"; } else { echo "Upload failed"; } echo ""; echo '
';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "
"; ?>
i need that all files uploaded are sequential such as 1,jpg 2,jpg 3,jpg ....

Marco (Tue, 04/28/2015 - 18:49)

Permalink
Something is wrong with this code it started to delete files randomly

r0h4n (Tue, 06/07/2016 - 22:33)

Permalink
8 years O.O

r0h4n (Wed, 06/08/2016 - 22:19)

Add new comment

The content of this field is kept private and will not be shown publicly.