[英]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連接后,下載文件需要做什么?
<?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函數(如fopen , fread和fwrite)讀取文件並進行寫入。 您只需使用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.