*/ ?>

PHP to quickly rename files based on a CSV

Filed Under PHP/MySQL on 2007-02-27, 23:35

I love php/mysql. Almost all of my sites are written with this pair. I decided earlier this week that I needed to launch a new site. Basically splitting off part of an existing site into its own site. The code was already written and luckily I had kept it in my head to keep it portable, so that took approximately 20-30 minutes to move over, change some settings, test, etc. But the problem was the database, as it referenced folder names that would no longer be applicable since they were based on an auto incrementing number in the database. 228 folders to be exact. My first thought was, “No big deal, some manual renaming, it’ll take an hour or two.” I did 5 of them and said forget this. I exported the folder name and an identifying filename from the old database, then exported the same info from the new database, matched them up in Excel, killed the filename columns, and then exported a csv that contained the new foldername and the old foldername. A little php scripting and in seconds 200+ folders were renamed. Granted I had a few that had to be done manually, but only about 5 or 6. For anyone that cares, here’s the quick and dirty php code to rename based off of a csv list of newname,oldname.

<?php
$handle = fopen(“file.csv”, “r”);
while (($data = fgetcsv($handle, 1000, “,”)) !== FALSE) {
   if (rename(“$data[1]”, “$data[0]”)) {
    print “Rename: <font color=\”green\”>Success</font><br />\n”;
   } else {
    print “Rename: <font color=\”red\”>FAILED!</font><br />\n”;
   }
}
fclose($handle);
?>


Comments