如何使用PHP从SFTP下载文件?

7

我正在尝试使用PHP从SFTP服务器下载文件,但是我找不到任何正确的文档来下载文件。

<?php 
$strServer = "pass.com"; 
$strServerPort = "22";
$strServerUsername = "admin"; 
$strServerPassword = "password";
$resConnection = ssh2_connect($strServer, $strServerPort);
if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)) {
    $resSFTP = ssh2_sftp($resConnection);
    echo "success";
}
?>

一旦我建立了SFTP连接,我需要做什么才能下载文件?

1
@OZ_: 我知道...我已经这样编辑了。 - Bas Slagter
2个回答

6

使用纯PHP SFTP实现方式的phpseclib

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

5

一旦您打开了SFTP连接,您可以使用标准的PHP函数(例如fopenfreadfwrite)读取文件并进行写操作。只需使用ssh2.sftp://资源处理程序打开远程文件。

这是一个示例,将扫描目录并下载根目录中的所有文件:

// Assuming the SSH connection is already established:
$resSFTP = ssh2_sftp($resConnection);
$dirhandle = opendir("ssh2.sftp://$resSFTP/");
while ($entry = readdir($dirhandle)){
    $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r');
    $localhandle = fopen("/tmp/$entry", 'w');
    while( $chunk = fread($remotehandle, 8192)) {
        fwrite($localhandle, $chunk);
    }
    fclose($remotehandle);
    fclose($localhandle);
}

从PHP5.6开始,这段代码将无法正常工作并且会默默失败:<pre><code> $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r'); </code></pre> $resSFTP应该显式转换为整数:<pre><code> $remotehandle = fopen('ssh2.sftp://' . intval($resSFTP) . '/$entry', 'r'); </code></pre> - Valery Lourie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接