3

I'm new to PHP and I'm trying to do something similar to what user580950 asked about at Bulk Rename Files in a Folder - PHP .

I want to write a script that will iterate over the names of all the files and directories in a given directory and do two things: replace the spaces with dashes and convert all caps to lowercase.

Based on the answer in the aforementioned question, and the PHP manual entries for the required functions, I came up with the following code:

if ($handle = opendir('/Users/username/Documents/School')) {

    while (false !== ($file_name = readdir($handle))) { 
        $to_lower = strtolower($file_name);
        $add_dashes = str_replace(" ", "-", $to_lower);
        rename($file_name , $add_dashes);
    }

    closedir($handle);
}

This code returns the following error for every single file/directory in the target directory:

Warning: rename(THE 273,the-273): No such file or directory in /Users/username/Sites/PHP/rename_files_in_directory.php on line 8

I've tried rearranging things in all kinds of ways, and I am completely stumped as to where the trouble is. I'm running PHP 5.3.8 on Mac OSX.6.8 .

Help will be greatly appreciated!

Community
  • 1
  • 1
John Aten
  • 73
  • 4

2 Answers2

2

You need to escape spaces. Try renaming directly using:

<?php

if ($handle = opendir('/Users/username/Documents/School')) {

    while (false !== ($file_name = readdir($handle))) { 
        $to_lower = strtolower($file_name);
        $add_dashes = str_replace(" ", "-", $to_lower);
        exec("mv ".escapeshellarg($file_name). " ". $to_lower);
        }

    closedir($handle);
    }
?>
raidenace
  • 12,789
  • 1
  • 32
  • 35
  • @Raidence , Although, when I tried the same script with the path to a different directory, I get a similar error: `Warning: rename(Sivulka 3,6,7 analysis.odt,sivulka-3,6,7-analysis.odt): No such file or directory in /Users/username/Sites/PHP/rename_files_in_directory.php on line 8 usage: mv [-f | -i | -n] [-v] source target mv [-f | -i | -n] [-v] source ... directory` Does it matter if the entries are files or directories? – John Aten Sep 07 '12 at 02:01
  • No, it does not matter, I tried creating `Sivulka 3,6,7 analysis.odt` as both dir and file and renamed them both successfully using the script above. Were you able to rename other files in that dir? – raidenace Sep 07 '12 at 13:50
  • The first directory I tried it on contained only other directories. I tried changing the path to another directory and got errors, as far as I can see nothing is different except the path. – John Aten Sep 08 '12 at 17:30
1
$path = '/Users/username/Documents/School';
[...]
rename("$path/$file_name", "$path/$add_dashes");
[...]

or

chdir ('/Users/username/Documents/School');

before your code.

  • I ultimately didn't need to do this, but I did try it and I got the same error as before, with an additional 'division by zero' error. – John Aten Sep 06 '12 at 18:52