Bulk Rename Files in a Folder (php)

im trying to rename images inside folder with php. i found out the exact what i want in site below
https://www.hashbangcode.com/article/sequentially-rename-all-image-files-directory-php

but its not renaming my images inside the folder
//xampp path ‘htdocs\e4\3’

$path = 'e4/3/';
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++;
 }
}

where im doing mistake… please correct me and guide me.

Where are you calling sequentialImages?

yes i have call function like below right after function ends:
function sequentialImages($path, $sort=false) {
}
sequentialImages(‘e4/3’);

After adding DIR to function its working but its adding zero (‘0’) infront of every rename files like: 01.jpg, 02.jpg, 03.jpg

number zero is being added by code below:
$newname = str_pad($i, strlen($count), ‘0’, STR_PAD_LEFT);

but i want simply as : 1.jpg, 2.jpg … 10.jpg,11jpg, 12.jpg

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), '0', STR_PAD_LEFT);
  $ext = substr(strrchr($file, '.'), 1);
  $newname = $path.'/'.$newname.'.'.$ext;
  if ( $file != $newname ) {
   rename($file, $newname);  
   echo 'file rename';
  }
  $i++;
 }
}
sequentialImages(__DIR__);

Surely you would just change that line so it doesn’t do the zero-padding. Something like

$newname = $i;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.