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

时间:2011-09-14 08:31:27

标签: php download sftp

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

2 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

打开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);
}