Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP download from remote server via sftp

Tags:

file

php

sftp

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.

like image 619
user2589167 Avatar asked Jul 16 '13 21:07

user2589167


People also ask

What is SFTP PHP?

Learn how to connect to SFTP, list files, upload and download using the PHP programming language. Guides Engineering. SFTP is a standard and secure protocol through which parties can safely transfer and share data and files. In any case, engaging with an SFTP server programatically can be challenging.

What is SSH2 SFTP?

The SSH2 File Transfer Protocol (SFTP), supported by Cerberus FTP Server Professional and higher, is a network protocol that provides secure and reliable file access, file transfer, and file management functionality.


1 Answers

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}")
like image 70
Prix Avatar answered Oct 21 '22 03:10

Prix