Sep 04

This is a simple script to go though a files inside a folder recursively and append the folder name to the file name.

The script is written for a windows system, just replace the \\ to / for unix.


function getDirectory( $path = '.', $level = 0 )
{    $dir_separator = '__';
 $ignore = array( 'cgi-bin', '.', '..','default.asp','index.php','PUT SELF IN THERE' );
 // Directories to ignore when listing output. Many hosts
 // will deny PHP access to the cgi-bin.

 $dh = @opendir( $path );
 // Open the directory to the handle $dh

 while( false !== ( $file = readdir( $dh ) ) ){
 // Loop through the directory

 if( !in_array( $file, $ignore ) && !strstr($file, $dir_separator))
 {    // Check that this file is not to be ignored
 //AND ALSO CHECK IF WE HAVENT ALRADY DONE THIS

 $spaces = str_repeat( ' ', ( $level * 4 ) );
 // Just to add spacing to the list, to better
 // show the directory tree.

 if( is_dir( "$path\\$file" ) )
 {    // Its a directory, so we need to keep reading down...

 //echo "<strong>$spaces $file</strong><br />";
 getDirectory( "$path\\$file", ($level+1) );
 // Re-call this same function but on a new directory.
 // this is what makes function recursive.
 } else {
 $rooot_path = 'C:\\xampp\\htdocs\\Documents';
 $old_filename = $rooot_path.substr("$path\\$file",1);
 $new_filename = substr($path,2);
 $new_filename = $rooot_path.substr('.\\'.$new_filename.'\\'.str_replace('\\',$separator,$new_filename).$separator.$file,1);
 echo "$old_filename -> $new_filename <br />";
 rename($old_filename,$new_filename);
 }
 }

 }
 closedir( $dh );
 // Close the directory handle
}

//run the function
getDirectory( "." );

2 Responses to “Recursively append folder name to file name”

  1. John Crudden Says:

    gday there, simply wished to mention thanks for this post, it let me become aware of something I didnt given much deliberation to it until now.

  2. Concetta Dow Says:

    I found your post very informative. thankyou very much!

Leave a Reply