Monday, March 09, 2009

PHP: how to rename a bunch of files / Windows XP

last weekend i was looking for a solution to rename a bunch of .mp3 files that had underscores and small letters as filenames while i prefered spaces instead of the underscores and capital letters for the individual words of the filename.

fortunately PHP has some built in functions to replace one character with another as well as renaming files altogether. i assumed that someone had already done something like it, so i went looking for a code-snippet on the internet again.

i came across this link.

this person was struggling with the renaming of some image files. i started to try the examples and various explanations as given when i stumbled across the problem that Windows XP is a bit fuzzy about renaming files. just search this document for Permission Denied and you'll know what i mean.

here's one solution:

function rename_win($oldfile,$newfile) {
if (!rename($oldfile,$newfile)) {
if (copy ($oldfile,$newfile)) {
unlink($oldfile);
return TRUE;
}
return FALSE;
}
return TRUE;
}


but that one didn't work for me either. another problem i had was defining the directory that contained the files to be renamed. after a number of struggles i came up with this solution:

first i placed all the .mp3 files into one folder together with the following code-snippet i saved to a file that i named rename-a-file.php.

<?php
// source: http://forum.de.selfhtml.org/archiv/2004/11/t95097/
$handle = opendir ('.');
while ( $file = readdir ( $handle ) ) {
if ( $file == "." or $file == ".." ) {
} else {
if ( rename( $file, (ucwords(str_replace('_',' ',$file).$new)) ) ) {
echo "File $file found <br>";
} else {
echo "File $file not found <br>";
}
}
} closedir( $handle );
?>


running the script at first i didn't see the changes in the folder until i pressed the refresh button. now all the files had no more underscores and capital letters, even the rename-a-file.php which is now called Rename-a-file.php :-)

i keep the Rename-a-file.php file now in a separate folder named rename that i may not accidentally run the script and rename the files in the folder where i kept the copy originally, with all my other .php files.

here is another example, in this case i didn't need to replace any characters; i only needed to change the lowercase to uppercase characters:

<?php
// source: http://forum.de.selfhtml.org/archiv/2004/11/t95097/
$handle = opendir ('.');
while ( $file = readdir ( $handle ) ) {
if ( $file == "." or $file == ".." ) {
} else {
if ( rename( $file, (ucwords($file).$new) ) ) {
echo "File $file found <br>";
} else {
echo "File $file not found <br>";
}
}
} closedir( $handle );
?>


in these examples i have used the following PHP functions:

opendir
readdir
rename
ucwords
str_replace
closedir

Hopefully this may prove helpful to other users, too. Don't overdo it!

tom.paine


No comments: