PHP File Rename – Command Line style

Posted: 2010/08/02 in PHP

Problem: Rename all files in a folder by their creation timestamp – take into account that there may be more than one file created in a given second (an issue on Windows timestamping).

My wonderful wife has provided me numerous opportunities create solutions to situations she may not have even thought of as a problem.. And is always gracious in giving me time to code (we have 2 wonderful kids) and is grateful for the results. I’m blessed. Anyway, she comes home from photographing a wedding and needs all the images taken from two different cameras (or up to 4 if there is a second shooter) put into time-stamp order before she begins editing. Thus, I need to rename all the files by their creation time.

Solution: PHP-CLI (’cause PHP just makes life simple)

I created a very simple script that renames all files in a directory by their timestamp. This is the first-attempt of this so there is no passing arguments, etc.  yet.   Just ‘cd’ to the desired directory and run the script from the command line.

And here it is:

  * This code is free software; you can use it, redistribute it, and/or modify as you wish.
  * This code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY - implied or otherwise.
  * This code is distributed "as is."  All risk and cost are assumed by the user of the code and not the creator thereof.
  * If you want to give attribution to the original creator of the original code, his name is David Malouf and he is, probably, available at
////  Rename files in TIMESTAMP order, with sequence add-on if needed  ////

date_default_timezone_set('America/Los_Angeles'); // for Windows to not freak out

$currentFile = $_SERVER['PHP_SELF'];

// Get list of files by date
$desiredDirectory = ".";       // current directory, in this example
$dirListing = new DirectoryIterator($desiredDirectory);

// Create array (fileTimeArray) where key = Filename and value = timestamp
foreach ($dirListing as $FileName) {
   if (!$FileName->isDot() && !$FileName->isDir() && $FileName != $currentFile) {
      $safeFile = filter_var($FileName->getFilename());
      $timestamp = date('Md__H_i_s', $FileName->getMTime());
      if (strpos ($safeFile, '.')) {      // add extension, if there is one
         $timestamp = $timestamp . substr($safeFile, strrpos($safeFile, '.'));
      $fileTimeArray[$safeFile] = $timestamp;

// Get list of duplicate time-stamps, to be used to add a sequece # to end of each timestamp
$DuplicateTimesArray = array_unique(array_diff_assoc($fileTimeArray,array_unique($fileTimeArray)));

// for each duplicated timestamp, add incrementing '_#' to end of timestamp
foreach ($DuplicateTimesArray as $DuplicateTime) {
   $allTheSame = array_intersect ($fileTimeArray, array($DuplicateTime));
   $i = 1;
   foreach ($allTheSame as $key=>$value) {
      $seqNum = sprintf("%01u", $i++);
          // pads with 0s to make at least a certain number of digits, zero-padded
          //  the number of total digits is represented by the number after the
          //  "%0  and before the "u" -- "%02u" would be a 2-digit, 0 padded number
      if (strpos ($value, '.')) {
         $fileTimeArray[$key] = substr($value,0,strrpos($value,'.')) . '_' . $seqNum . substr($value,strrpos($value,'.'));
      } else {
         $fileTimeArray[$key] = $value . '_' . $seqNum;

//// Rename files
 // set current Directory
if (strpos($_SERVER['OS'], 'ind')) {
         // command-line, WINDOWS (Win = position 0 == false, using 'ind' of Windows)
   $currentDir = getcwd() . '\\';
} else if (strpos($_SERVER['OSTYPE'], 'inux')) {
        // command-line, LINUX (see above for 'missing "l" ')
   $currentDir = $_SERVER['PWD'] . '/';
} else {
   $currentDir = substr($_SERVER['SCRIPT_FILENAME'],0,strrpos($_SERVER['SCRIPT_FILENAME'], '/')) . '/'; // Webpage

 // rename files
foreach ($fileTimeArray as $fileName=>$timeStamp) {
   $fullOld = $currentDir . $fileName;
   $fullNew = $currentDir . $timeStamp;
   rename ($fullOld, $fullNew);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s