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