7

This may have been asked before, I'm new to PHP and I'm trying to learn as much as I can, but this has really thrown me.

Basically what I want to know is, how would I use PHP code to get it to download everything from a remote server to a local location. It's getting it to download everything not just one file that I'm stuck on. So please can someone show/explain to me how I would do this?

What I've got so far:

<?php
$connection - ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$remote_dir="/remote_dir/";
$local_dir="/local_dir/";

$remote ="$remote_dir";
$stream = ssh2_exec($connection, $remote);
stream_set_blocking($stream,true);
$command=fread($stream,4096);

$array=explode(\n,$command);

$total_files=sizeof($array);

for($i=0;$i<$total_files;$i+++){
    $file_name=trim($array[$i]);
    if($file_name!=''{
        $remote_file=$remote_dir.$file_name;
        $local_file=$local_dir.$file_name;

        if(ssh2_scp_recv($connection, $remote_file,$local_file)){
            echo "File ".$file_name." was copied to $local_dir<br />"; 
        }
    }
}
fclose($stream);
?>

I think my $remote ="$remote_dir"; is wrong, and to be honest I've got $filename when I want the whole directory, this is all I have so far.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
user2589167
  • 73
  • 1
  • 1
  • 5
  • 3
    Post what you have done so far and don't forget to replace any sensitive information if any. – Prix Jul 16 '13 at 21:52
  • Just added what I've got so far. like I said I dunno if it's right or not only started PHP a few weeks ago, but I'm probably over my head here. – user2589167 Jul 16 '13 at 22:30
  • Have posted a sample hope you like, since you're new to Stackoverflow [**I also recommend you to take a trip to the Stackoverflow Tour to know how to best use this website which will help you greatly fr future questions.**](http://stackoverflow.com/about) – Prix Jul 16 '13 at 23:56

3 Answers3

27

Here is a small code on how to read the folder and download all its files:

<?php
$host = 'localhost';
$port = 22;
$username = 'username';
$password = 'password';
$remoteDir = '/must/be/the/complete/folder/path';
$localDir = '/can/be/the/relative/or/absolute/local/path';

if (!function_exists("ssh2_connect"))
    die('Function ssh2_connect not found, you cannot use ssh2 here');

if (!$connection = ssh2_connect($host, $port))
    die('Unable to connect');

if (!ssh2_auth_password($connection, $username, $password))
    die('Unable to authenticate.');

if (!$stream = ssh2_sftp($connection))
    die('Unable to create a stream.');

if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
    die('Could not open the directory');

$files = array();
while (false !== ($file = readdir($dir)))
{
    if ($file == "." || $file == "..")
        continue;
    $files[] = $file;
}

foreach ($files as $file)
{
    echo "Copying file: $file\n";
    if (!$remote = @fopen("ssh2.sftp://{$stream}/{$remoteDir}{$file}", 'r'))
    {
        echo "Unable to open remote file: $file\n";
        continue;
    }

    if (!$local = @fopen($localDir . $file, 'w'))
    {
        echo "Unable to create local file: $file\n";
        continue;
    }

    $read = 0;
    $filesize = filesize("ssh2.sftp://{$stream}/{$remoteDir}{$file}");
    while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
    {
        $read += strlen($buffer);
        if (fwrite($local, $buffer) === FALSE)
        {
            echo "Unable to write to local file: $file\n";
            break;
        }
    }
    fclose($local);
    fclose($remote);
}

You can also resume this code to (it will not copy directories):

while (false !== ($file = readdir($dirHandle)))
{
    if ($file == "." || $file == "..")
        continue;

    echo "Copying file: $file\n";
    if(!ssh2_scp_recv($connection, $remoteDir . $file, $localDir . $file))
        echo "Could not download: ", $remoteDir, $file, "\n";
}

If you do not use the full path on the remote folder it will not work:

opendir("ssh2.sftp://{$stream}{$remoteDir}")
Scott Arciszewski
  • 33,610
  • 16
  • 89
  • 206
Prix
  • 19,417
  • 15
  • 73
  • 132
0

Update: I was kindly corrected that this doesn't use sftp, but instead uses ftps. Here's a Stackoverflow link discussing using PHP to do SFTP.

The PHP docs already cover most of what you should need for this. Here's an example for fetching a list of the contents in the remote directory:

<?php
// set up basic connection
$ftp_server = "example.com";
$conn_id = ftp_ssl_connect($ftp_server);

// login with username and password
$ftp_user_name = "myuser";
$ftp_user_pass = "mypass";
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_pasv($conn_id, true);
// check connection
if ((!$conn_id) || (!$login_result)) {
        echo "FTP connection has failed!";
        echo "Attempted to connect to $ftp_server for user $ftp_user_name";
        exit;
    } else {
        echo "Connected to $ftp_server, for user $ftp_user_name";
    }

$buff = ftp_rawlist($conn_id, '.');
 var_dump($buff);
ftp_close($conn_id); 
?> 
Community
  • 1
  • 1
Arth Du
  • 807
  • 4
  • 6
  • Thanks for the quick reply! So using this I can check the list of everything at the directory, and using the ftp_ssl is the same as using a SFTP? – user2589167 Jul 16 '13 at 21:58
  • Yes. This will give you a listing of all the files in the directory and you are using SSL which is SFTP – Arth Du Jul 16 '13 at 22:15
  • 3
    NO they are not the same thing, SFTP is SSH File Transfer Protocol while FTP over SSL also known as FTP Secure and FTP-SSL, here is a good article https://www.eldos.com/security/articles/4672.php – Prix Jul 16 '13 at 22:45
  • You and me both, thanks for the help so I'll be using things like ssh_ etc then? – user2589167 Jul 16 '13 at 22:51
  • I updated my answer with a link to another SO discussion on using PHP to do SFTP – Arth Du Jul 16 '13 at 22:52
0

Here you will find all the examples for what you can do with SFTP using PHP. http://phpseclib.sourceforge.net/sftp/examples.html

<?php
   include('Net/SFTP.php');

   $sftp = new Net_SFTP('www.domain.tld');
   if (!$sftp->login('username', 'password')) {
       exit('Login Failed');
   }

   // outputs the contents of filename.remote to the screen
   echo $sftp->get('filename.remote');
   // copies filename.remote to filename.local from the SFTP server
   $sftp->get('filename.remote', 'filename.local');
?>
Sami Haroon
  • 869
  • 10
  • 14