2nd March 2009 - 3 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.