Jump to content

Archived

This topic is now archived and is closed to further replies.

Moon-Man.net

Directory Browsing

Recommended Posts

Hey all,
I have a script that will replace any files in a given directory with banned Charactures, However, how can i make this script be reocursive? EG. will also replace files in subdirectories of the given dir. I am totally stuffed for that:S
Thanks heaps EVERYONE for their help!
Cheers,
Nathan

[code]
#!/usr/bin/php
<?PHP
$dir = '/tmp/TESTING';
$handle = opendir($dir);
$cnt=0;

echo "<------------Starting Replace!------------>\n" ;
echo "\n";
while(($file = readdir($handle)) !== false){
// echo "File found: " .$file ."\n";
    if (preg_match('/[' .preg_quote('\/ : * ? " < > |', '/') .']/', $file)){
echo "Bad file found: " .$file ."  " ;
$cnt++ ;
        $path = $dir . DIRECTORY_SEPARATOR . $file;
        if (!in_array($file, array('..', '.')) && is_file($path)){
            $contents = file_get_contents($path);
            $newPath = $dir . DIRECTORY_SEPARATOR . preg_replace('/[' .preg_quote('\/ : * ? " < > |', '/') .']/', '', $file);
            echo "Replacing with " .$newPath ."\n" ;
//          if (file_put_contents($newPath, $contents) !== false){
//              unlink($path); //delete old file only if able to create new
//          }
        }
    }
}
echo "\n";
echo "\n";
echo "<------------Replace Finnished------------>\n" ;
echo "There were " .$cnt ." Replacements Made\n" ;
?>
[/code]

Share this post


Link to post
Share on other sites
[code]function replace_bad_files($dir) {
  $handle = opendir($dir);
  ...
  while (($file = readdir($handle)) !== false) {
    # If we found a directory, call ourselves again!  Simple
    $path = $dir . DIRECTORY_SEPARATOR . $file;
    if (is_dir($path)) {
      replace_bad_files($path);
      continue; # This will skip to the next file
    }
    ...
  }
}[/code]

The important steps here are

[list]
[*]Make a function
[*]Call the function recursively when you find a directory (as indicated by is_dir())
[/list]

To count the global number of replacements, you can either use a global variable, or you can have your function return the count, by adding "return $cnt;" at the end.  In that case, the recursive call should be "$cnt += replace_bad_files($path)".

Share this post


Link to post
Share on other sites
Awesome, so i can have a

[code]
if(is_dir($file)){
replace_bad_file($file) ;
}
[/code]
Somewhere in there, and it will keep opening all unlimited ammounts of functions untill it is totally re-ocursive :D
I diddnt know you call call the function you are in from within it :)
Thanks Heaps.
Cheers,
Nathan

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.