[英]How to download a file from SFTP using PHP?
I am trying to download a file from an sftp server using php but I can't find any correct documentation to download a file. 我试图使用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";
}
?>
Once I have the SFTP connection open, what do I need to do to download a file? 打开SFTP连接后,下载文件需要做什么?
Using phpseclib, a pure PHP SFTP implementation : 使用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');
?>
Once you have your SFTP connection open, you can read files and write using standard PHP functions such as fopen , fread , and fwrite . 打开SFTP连接后,可以使用标准PHP函数(如fopen , fread和fwrite)读取文件并进行写入。 You just need to use the
ssh2.sftp://
resource handler to open your remote file. 您只需使用
ssh2.sftp://
资源处理程序打开您的远程文件。
Here is an example that will scan a directory and download all files in the root folder: 这是一个扫描目录并下载根文件夹中所有文件的示例:
// 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.