Sifur Sifur - 1 year ago 70
PHP Question

Rename files with its directory name

I have some directories with files like:


And I want to rename all files inside all directories with its corresponding directory name (but keeping its extension), like:

folder1/filename.jpg to folder1/folder1.jpg
folder2/filename.pdf to folder2/folder2.pdf
folder3/filename.jpg to folder3/folder3.jpg

Edit: also, I want to copy all renamed files to another directory (like "allfiles").

I found a similar question in Perl language.

How could I achieve it with PHP?

Answer Source

Here you have a way to do that:


// Array with all subdirectories in directory
$dirArray = array_filter(glob('/path/to/directory/*'), 'is_dir');

// $dir is the path to the subdirectory
foreach ($dirArray as $dir) {

    // $dirName has the future name of files in that subdirectory
    $dirName = basename($dir);

    // Take all the elements in the subdirectory (except '.' and '..')
    $filesArray = array_diff(scandir($dir), array('.', '..'));

    $i = 0;
    foreach ($filesArray as $file) {
        // Take the file extension for the rename method
        $fileExtension = pathinfo($file, PATHINFO_EXTENSION);

        $oldName = $dir . "/" . $file;
        $newName = $dir . "/" . $dirName . "-" . $i . "." . $fileExtension;

        rename($oldName, $newName);

If you are sure you will have only one file in each subdirectory you can use this line to $newName:

$newName = $dir . "/" . $dirName . "." . $fileExtension;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download