Sifur Sifur - 17 days ago 5
PHP Question

Rename files with the folder name in PHP

I found this
How can I do this with PHP.

What I want to do is,
I have some folders with files like:

folder1 --> filename.jpg
folder2 --> filename.pdf
folder3 --> filename.jpg


And I want to rename all files inside all folders with the folder name, like:

folder1 --> filename.jpg ==folder1.jpg
folder2 --> filename.pdf ==folder2.pdf
folder3 --> filename.jpg ==folder3.jpg


And after that copy all files to a directory like "allfiles"

Answer

Here you have a way to do that:

<?php

// 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);
        $i++;
    }
}

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

$newName = $dir . "/" . $dirName . "." . $fileExtension;
Comments