0

I am connecting to another server via php's ftp connect.

However I need to be able to extract all html files from it's web root which is causing me a bit of a headache...

I found this post Recursive File Search (PHP) which talks about using RecursiveDirectoryIterator function however this is for a directory on the same server as the php script its self.

I've had a go with writing my own function but not sure I've got it right... assuming that the original path sent to the method is the doc root of the server:

public function ftp_dir_loop($path){

    $ftpContents = ftp_nlist($this->ftp_connection, $path);

    //loop through the ftpContents
    for($i=0 ; $i < count($ftpContents) ; ++$i)
        {
            $path_parts = pathinfo($ftpContents[$i]);

            if( in_array($path_parts['extension'], $this->accepted_file_types ){

                //call the cms finder on this file
                $this->html_file_paths[] = $path.'/'.$ftpContents[$i];

            } elseif(empty( $path_parts['extension'] )) {

                //run the directory method
                $this->ftp_dir_loop( $path.'/'.$ftpContents[$i] );  
            }
        }
    }   
}

Has anyone seen a premade class to do something like this?

Community
  • 1
  • 1
  • This should do it, though nlist() returns false on errors like path cannot be found or is a file, you should check for that. – Ja͢ck Oct 31 '12 at 22:17
  • Btw, perhaps more reliable way to detect directory is by using "-al $path" as 2nd argument to ftp_nlist(). – Ja͢ck Oct 31 '12 at 22:35

1 Answers1

0

You can try

public function ftp_dir_loop($path) {
    $ftpContents = ftp_nlist($this->ftp_connection, $path);
    foreach ( $ftpContents as $file ) {
        if (strpos($file, '.') === false) {
            $this->ftp_dir_loop($this->ftp_connection, $file);
        }
        if (in_array(pathinfo($file, PATHINFO_EXTENSION), $this->accepted_file_types)) {
            $this->html_file_paths[$path][] = substr($file, strlen($path) + 1);
        }
    }
}
Baba
  • 94,024
  • 28
  • 166
  • 217
  • I don't see the usefulness in throwing away the path leading up to the file itself. – Ja͢ck Oct 31 '12 at 22:23
  • although can't a directory have a dot at the end which would cause the directory test to fail? I know you can in macOS at least.. –  Nov 01 '12 at 00:45
  • The condition also fails if the path is set to '.', since the returned files contain this path, for example './photos'. – Jort May 20 '15 at 11:52