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

SAN*_*122 6 php sftp download

我试图使用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";
}
?>
Run Code Online (Sandbox Code Playgroud)

打开SFTP连接后,下载文件需要做什么?

小智 6

使用phpseclib,一个纯PHP SFTP实现:

<?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');
?>
Run Code Online (Sandbox Code Playgroud)


nul*_*ity 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);
}
Run Code Online (Sandbox Code Playgroud)