Check remote directory using PHP SSH2

How to check if xyz directory exists on a remote SSH server using PHP-SSH2?

+6
source share
5 answers

You can use file_exists using the sftp prefix 'ssh2.sftp: //'

For example, with a steady connection, you can:

$sftp = ssh2_sftp($connection); $fileExists = file_exists('ssh2.sftp://' . $sftp . '/home/marco'); 
+16
source

I would recommend abandoning PHP SSH2 instead of phpseclib, a pure implementation of PHP SSH .

Among other things, the PHP SSH2 API sucks. Private keys must be stored on a bootable file system, while phpseclib all they need is a string. You can take the key from $ _POST without having to upload it to the file system, as libssh2 requires. For this, libssh2 requires that you have a separate file for the public that is dead by the brain, since the private key contains the public key.

ssh2_exec (), from libssh2, also returns ANSI color codes and sometimes never returns and sometimes does (this is inconsistent).

Finally, phpseclib is simply faster .

+3
source

This is assumed to be a linux server

 $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $cmd = 'if test -d "/YOUR_DIRECTORY"; then echo 1; fi'; $stream = ssh2_exec($connection, $cmd); 
+1
source
  <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $stream = file_exists("ssh2.sftp://$sftp/path/to/file"); ?> 
0
source

To check if a remote path is a folder or file using PHP_SSH2

 $path="/tmp"; $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $sftp = ssh2_sftp($connection); $isdir = is_dir("ssh2.sftp://$sftp/$path"); if ( $isdir ==true) { echo "The Remote Folder is a Directory".PHP_EOL; } else { $isfile = file_exists("ssh2.sftp://$sftp/$path"); if ($isfile == true) { echo "The Remote Path is a File".PHP_EOL; } } 
0
source

Source: https://habr.com/ru/post/890916/


All Articles