Jump to content

Directory Browsing


Moon-Man.net

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]
Link to comment
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)".
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.