ARTICLE AD BOX
Finalized the FTP class now.
For my usage - having a recursive file listing, it works great.
Maybe a bit complicated written, but it's just ~70 lines of code.
My goal in my request was to find the error was thrown. After it was identified, the class got optimized and works now as expected.
This is the class:
<?php class FTP { private $connection, $server; private $files = []; function __construct($server) { $this->server = $server; $this->connect(); } private function connect() { $this->connection = ftp_connect( $this->server->host, $this->server->port ); ftp_login($this->connection, $this->server->username, $this->server->password ); ftp_chdir($this->connection, $this->server->working_directory); return $this; } public function get_files($path = ".") { $path == "." ? $path = "" : $path = $path; return ftp_nlist($this->connection, $path); } public function get_fiels_recursive($path = ".", $max_level = 0) { $path == "." ? $path = "" : $path = $path; $this->files = []; return $this->get_remote_files($path, $max_level); } private function get_remote_files($path, $max_level, $level = 0) { $remote_object_list = $this->convert_raw_list(ftp_rawlist($this->connection, $path)); foreach ($remote_object_list as $remote_object) { $remote_path = $path . $remote_object->name . "/"; if ($remote_object->is_directory && $max_level != 0) { if ($level < $max_level || $max_level == -1) { $current_level = $level + 1; $this->get_remote_files($remote_path, $max_level, $current_level); } else { array_push($this->files, dirname($remote_path) . "/" . $remote_object->name); } } else { array_push($this->files, dirname($remote_path) . "/" . $remote_object->name); } } return $this->files; } private function convert_raw_list($raw_list) { $raw_object_list = []; $matches = []; $pattern = "/(?:([\w\-]*\s*\w*\s*\w*\s*\w*\s*\w*\s*\w*\s*\w*\s*[\w\:]*\s))([\w\W]*)/"; foreach ($raw_list as $raw) { preg_match($pattern, $raw, $matches); $object = new stdClass(); $object->is_directory = substr($matches[1], 0, 1) == "d" ? true : false; $object->name = $matches[2]; array_push($raw_object_list, $object); } return $raw_object_list; } }You can call get_files or get_files_recursive
An example (please define your $server object yourself) - this is recursive with unlimited deep of level:
$ftp = new FTP($server); $files = $ftp->get_fiels_recursive(".", -1);Another example (please define your $server object yourself) - this is recursive up to deep level 1:
$ftp = new FTP($server); $files = $ftp->get_fiels_recursive(".", 1);Another example (please define your $server object yourself) - this is not recursive:
$ftp = new FTP($server); $files = $ftp->get_fiels(".");You can also set the 1st parameter to any existing folder in the FTP structure.
Hope that helps some. For me it was a mess to look for such a function (now in a class).
Feel free to grab and optimize. You can also copy/paste to use for any public/private git. No restrictions from my side. Complete open.
