Friday, September 11, 2009

How to rename multiple files in a directory with php

The following example will tell you how to rename more than one file using php
<?
php
$dir = "C:\\vaseem\\rename_files";
$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 "<br/>";
$count++;
}
else
{
echo "Cannot rename ".$file. " to ".$newName."<br/>";
echo "<br/>";
}
}
}
}
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".


0 comments:

Post a Comment

 

About Me

My photo
Hey guys this is Vaseem Ansari, 25 years old, Software & Web Developer, Blogger & works on Open Sources Technologies I love my family and my loved once very much. It takes a while for me to build trust in someone new. I am honest, thoughtful, and my friends tell me that I am wise. I would also say that I am stubborn. but I do learn from my mistakes. I'm Glad I'm Me No one looks The way I do. I have noticed That it's true. No one walks the way I walk. No one talks the way I talk. I am me. There's no one else I'd rather be! Have fun reading this blog and don't forget to subscribe to the feed to keep updated on the latest articles. Visit my Blog at http://www.VaseemAnsari.com/blog/

Followers