PHP bulk rename, with more than one renaming function

846

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!

43

Answer

Solution:

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);
    }
?>
879

Answer

Solution:

$path = '/Users/username/Documents/School';
[...]
rename("$path/$file_name", "$path/$add_dashes");
[...]

or

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

before your code.

People are also looking for solutions to the problem: javascript - How to pass php code in this in label_htm i want to show count number in this filed

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.