通过 sftp 从远程服务器下载 PHP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17687607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:15:02  来源:igfitidea点击:

PHP download from remote server via sftp

phpfilesftp

提问by user2589167

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.

之前可能有人问过这个问题,我是 PHP 的新手,我正在努力学习尽可能多的知识,但这确实让我感到困惑。

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?

基本上我想知道的是,我将如何使用 PHP 代码让它将所有内容从远程服务器下载到本地位置。它可以下载所有内容,而不仅仅是我卡住的一个文件。所以请有人向我展示/解释我将如何做到这一点?

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.

我想我的 $remote ="$remote_dir"; 是错误的,老实说,当我想要整个目录时,我已经有了 $filename,这就是我目前所拥有的。

回答by Prix

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}")

回答by Arth Du

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.

更新:我被亲切地纠正,这不使用 sftp,而是使用 ftps。这是讨论使用 PHP 执行 SFTP的 Stackoverflow 链接。

The PHP docsalready 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文档已经覆盖了大部分的,如果您需要什么这一点。这是获取远程目录中内容列表的示例:

<?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); 
?>