How to rename files in a directory with php
Recently I came across a situation where I needed to rename more then 100 mp3 files. For some reason I had to remove first 4 characters from each file name. Rather then renaming each file manually, I thought of writing a small php script that renamed all these files for me.
I would like to share that with you, so here goes the code.
$dir = "F:\\Music\\php_test";
$fileType = "mp3";
$charsToTrim = 4;
if($handle = opendir($dir))
{
$count = 1;
while (false !== ($file = readdir($handle))) // read files in directory one by one
{
if(is_file($dir."\\".$file))
{
$extension = substr(strrchr($file,"."),1);// get the extension
if(strcasecmp($fileType,$extension) == 0)// proceed only if it matches with the extension we have provided
{
$newName = substr($file,$charsToTrim); // generate new name for file
$success = rename($dir."\\".$file, $dir."\\".$newName); // rename the file
if($success)
{
echo $file." renamed to ".$newName;
echo "
";
$count++;
}
else
{
echo "Cannot rename ".$file. " to ".$newName."
";
echo "
";
}
}
}
}
echo $count." files renamed";
}
closedir($handle);
You will have to set these 3 parameters:
$dir – Location of directory in which files are placed.
$fileType – Extension of files that you want to rename(mp3 or txt or doc any other)
$charsToRemove – How many characters do you wish to remove from the filename.
Set these and you are ready to rename. Remember that this script will only trim characters from start of the file name.
This means if you have set $charsToRemove = 5, a file with name “abcd_Plateau” will be renamed to “Plateau”.
Waiting for comments and suggestions.
Related Posts
4 Comments to “How to rename files in a directory with php”
Add Comments (+)-
-
hi
it’s very usefull.
I need to delete last char’s and add some char’s before “.”
plz help me. -
I want to say thank you for this script. It helped my work. Thank you.

Hey man!
This is very nice, practic and easy script…. well done!
Could you make something like advanced file rename-er?
Something like this:
Delete first char’s;
Delete last char’s;
Add first char’s;
Add last char’s;
Or maybe to add ID2&ID3 tag to mp3 files at this case
C-ya