I would like to list the files of a directory in an other server
I am connected to an other server using ssh2_connect function the connection is going well and I am
Here's a method which can scan directories recursively and return multi-dimensional arrays if the recursive parameter is set, or only scan the path and return a single dimension array containing files in that directory if it's not. Can be modified to also include directories without contents in non-recursive mode if needed.
Creating it as a class makes it easy to be reused later. I only included the methods from my class that were required to answer the question.
$host = 'example.com';
$port = 22;
$username = 'user1';
$password = 'password123';
$path = '.';
$recursive = true;
$conn = new SFTP($host, $port);
$conn->login($username, $password);
$files = $conn->ls($path, $recursive);
var_dump($files);
class SFTP
{
private $connection;
private $sftp;
public function __construct($host, $port = 22)
{
$this->connection = @ssh2_connect($host, $port);
if (! $this->connection)
throw new Exception("Could not connect to $host on port $port.");
}
public function login($username, $password)
{
if (! @ssh2_auth_password($this->connection, $username, $password))
throw new Exception("Could not authenticate with username $username");
$this->sftp = @ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
}
public function ls($remote_path, $recursive = false)
{
$tmp = $this->sftp;
$sftp = intval($tmp);
$dir = "ssh2.sftp://$sftp/$remote_path";
$contents = array();
$handle = opendir($dir);
while (($file = readdir($handle)) !== false) {
if (substr("$file", 0, 1) != "."){
if (is_dir("$dir/$file")){
if ($recursive) {
$contents[$file] = array();
$contents[$file] = $this->ls("$remote_path/$file", $recursive);
}
} else {
$contents[] = $file;
}
}
}
closedir($handle);
return $contents;
}
}