Trying to get all content of directory from one server to another using ssh2_scp_recv in php

2.4k Views Asked by At

The below script is working successfully.

Getting file from one server to another

if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp', 
    '/var/www/html/captures/store/2016/04/HK/15721022890870/test/vcredist.bmp')){
echo "\n recevied \n";
  }else{
 echo "\n not recevied\n";
  }

But instead for fetching just a static file, I want to fetch folder with all its content inside.

With above example, the directory I would like to fetch to local server is "15721022890870"

/var/www/html/captures/store/2016/04/HK/15721022890870/

I have tried below code but doesn't work,

The remote server has directory, but the local server doesn't have, so I want to make directory then copy all its content inside

if(ssh2_scp_recv($conn, '/var/www/html/captures/store/2016/04/HK/15721022890870/', 
    '/var/www/html/captures/store/2016/04/HK/')){
echo "\n recevied done \n";
  }else{
  echo "\n not done \n";
   }
1

There are 1 best solutions below

0
On
<?php
$username = "your_username";
$password = "your_pass";
$url      = 'your_stp_server_url';
// Make our connection
$connection = ssh2_connect($url);

// Authenticate
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect.');

// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create SFTP connection.');
$localDir  = '/path/to/your/local/dir';
$remoteDir = '/path/to/your/remote/dir';
// download all the files
$files    = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
  foreach ($files as $file) {
    if ($file != '.' && $file != '..') {
      ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
    }
  }
}
?>

This is from server to computer but you can modify the $localDir