Mass renaming images in PHP

Lets say you have a group of photos from a location, shoot or event. They will be named depending on the camera something like DC001984 or IMG_02891 something like that anyway.

There is no real organisation and certainly no indicator to what they are without viewing the thumbnail. Here is some PHP code to mass rename the images which is perfect if you’re going to mass upload them and want the name to be reflective for what the image are of.

The code is this:

<?php
$i = 0;//foreach loop counter
$dir = '';//'the/path/'
$context = 'location xyz 10 Jan 2019';//Name all files this (plus sequential number attached as per below)
foreach (glob($dir . '*.{arw,ARW,jpg,JPG,jpeg,JPEG,png,PNG}', GLOB_BRACE) as $file) {//all image files in $dir
    $i++;//plus 1
    rename($file, "$context $i.arw");//Rename file to context with sequential number attached at the end to differentiate
    echo "RENAMED: $file to $context $i.arw<br>";//Some optional output
}

Looping through all the images in the stated directory and renaming (using rename()) to what the $context is whilst adding the count value to the end of the file name to avoid “duplicates”.

Take this example of before:

php mass rename before

to then after:

php mass rename after

 

 

Then you can pick through the photos that will be used for SEO purpose and rename them to be more specific and identifying. Otherwise you now have photos that are named relevant and organised so much better than the default file naming.