This is an update to the code provided by dev at islam-soft dot com, which renames all files in a directory with a given extension to have a different extension.
I updated four things: Most important, added a check to make sure the extension matched ONLY the end of the filename (the original caused me a number of headaches when it started matching things in the middle of filenames instead of at the end where a proper extension belongs), 2nd added some feedback about what is going on, if you choose verbose mode=TRUE, 3rd added the "testing" parameter so you can do a test run before committing for real, 4th added an error message if a rename fails.
parameter 1 : the directory name
parameter 2 : the first extension which we want to replace
parameter 3 : the new extension of files
parameter 4 : verbose? (true/false)
parameter 5 : testing? (true/false)--if true, won't actually rename anything; if you do verbose=TRUE and testing=TRUE you can see what will happen before committing to it with testing=FALSE.
Return is the number of files renamed.
for a simple usage call the function :
changeext('my/directory', 'html', 'php', false, false);
This changes every file name with extension html into php in the directory my/directory
<?PHP
function changeext($directory, $ext1, $ext2, $verbose = false, $testing=true) {
if ($verbose && $testing) { echo "Testing only . . . <br />";}
$num = 0;
if($curdir = opendir($directory)) {
if ($verbose) echo "Opening $directory . . .<br />";
while($file = readdir($curdir)) {
if($file != '.' && $file != '..') {
$srcfile = $directory . '/' . $file;
$string = "$file";
$str = strlen($ext1);
$str++;
$newfile = substr($string, 0, -$str);
$newfile = $newfile.'.'.$ext2;
$dstfile = $directory . '/' . $newfile;
if (eregi("\.$ext1". '$' ,$file)) { $fileHand = fopen($srcfile, 'r');
fclose($fileHand);
if (!$testing) {
$result=rename($srcfile, $dstfile );
if (!$result) echo "ERROR renaming $srcfile -> $dstfile<br />";
}
if ($verbose) echo "$srcfile -> $dstfile<br />";
}
if(is_dir($srcfile)) {
$num += changeext($srcfile, $ext1, $ext2, $verbose, $testing);
}
}
}
closedir($curdir);
}
return $num;
}
$testing=true;
$verbose=true;