Recursively go through all the directories
Though this is a very simple task, it is a very intersting one to do because it can have many applications, like deleting files, renaming them based on a sequence, etc. In this code snippet, I’ve applied this technique to rename all the image files with extension “JPG” to “jpg” (to maintain standards and uniformity). So let’s dive in.
Create a file in named “rename.php”. and put this code in the file:
<?php
if(!$_GET["directory"])
{
$rootdir = ".";
}else{
$rootdir = $_GET["directory"];
}
function renameFiles($dir){
$fileList = scandir($dir) or die("Not a directory");
foreach($fileList as $file){
if(is_dir("$dir/$file") && $file != '.' && $file != '..')
{
renameFiles("$dir/$file");
}
if(is_file("$dir/$file"))
{
if(substr(basename("$dir/$file"), strlen(basename("$dir/$file")) - 3) == "JPG")
{
echo "$dir/$file" . "<br/>";
rename("$dir/$file", "$dir/" . substr(basename("$dir/$file"),0, strlen(basename("$dir/$file")) - 4) . ".jpg");
}
}
}
return $xmlStr;
}
renameFiles($rootdir);
?>
Now upload this to your server. If you want to rename all the images in a folder named “images”, upload it to your root and open it as http://www.example.com/rename.php?directory=images.
Happy coding!



