簡體   English   中英

如何使用PHP從SFTP下載文件?

[英]How to download a file from SFTP using PHP?

我試圖使用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連接后,下載文件需要做什么?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM