【问题标题】:How to download a file from SFTP using PHP?如何使用 PHP 从 SFTP 下载文件?
【发布时间】:2011-11-16 19:46:08
【问题描述】:

我正在尝试使用 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 连接后,我需要做什么才能下载文件?

【问题讨论】:

  • @OZ_:我知道...我是这样编辑的。

标签: php download sftp


【解决方案1】:

打开 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 开始,这将不起作用并且会静默失败:
     $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", ' r'); 
    $resSFTP 应显式转换为 int:
     $remotehandle = fopen('ssh2.sftp://' . intval($resSFTP) . '/$entry', ' r'); 
【解决方案2】:

使用phpseclib, a pure PHP SFTP implementation

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多