2011-09-14 57 views
6

我想從使用PHP的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連接,我需要做什麼來下載文件?

+1

所以,問題是什麼? –

+0

@Baszz閱讀標題。 –

+1

@OZ_:我知道......我是這樣編輯的。 –

回答

5

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

從PHP5.6開始,這將無法正常工作,並且會自動失敗:

 $remotehandle = fopen("ssh2.sftp://$resSFTP/$entry", 'r'); 
$ resSFTP應明確轉換爲int:
 $remotehandle = fopen('ssh2.sftp://' . intval($resSFTP) . '/$entry', 'r');