views:

738

answers:

3

How would one go about deleting all of the directories in a directory tree that have a certain name if the only access to the server available is via FTP?

To clarify, I would like to iterate over a directory tree and delete every directory whose name matches a certain string via FTP. A way to implement this in PHP would be nice - where should I start? Also, if anyone knows of any utilities that would already do this, that would be great as well.

+1  A: 

Presumably there's more to this question than it first appears.

FTP supports DIR to list directory contents, RMDIR to remove directories and DEL to delete files, so it supports the operations you need.

Or are you asking how to iterate over an FTP directory tree?

Do you have a preferred/required implementation language for this?

Paul
+4  A: 

Here is a starting point- a function that will scan through an FTP directory and print the name of any directory in the tree which matches the pattern. I have tested it briefly.

function scan_ftp_dir($conn, $dir, $pattern) {
    $files = ftp_nlist($conn, $dir);
    if (!$files) {
     return;
    }

    foreach ($files as $file) {
     //the quickest way i can think of to check if is a directory
     if (ftp_size($conn, $file) == -1) {

      //get just the directory name
      $dirName = substr($file, strrpos($file, '/') + 1);

      if (preg_match($pattern, $dirName)) {
       echo $file . ' matched pattern';
      } else {  
       //directory didn't match pattern, recurse 
       scan_ftp_dir($conn, $file, $pattern);
      }
     } 
    }
}

Then do something like this

$host = 'localhost';
$user = 'user';
$pass = 'pass';


if (false === ($conn = ftp_connect($host))) {
    die ('cannot connect');
}

if (!ftp_login($conn, $user, $pass)) die ('cannot authenticate');


scan_ftp_dir($conn, '.', '/^beginswith/');

Unfortunately you can only delete an empty directory with ftp_rmdir(), but if you look here there is a function called ftp_rmAll() which you could use to remove whole directory structures which you find.

Also I have only tested on Unix the trick of using the fail status returned from ftp_size() as a method of checking if an item returned by ftp_nlist() is a directory.

Tom Haigh
A: 
Steven Oxley