I am tryin开发者_StackOverflowg to download a file from an sftp server using php but I can't find any correct documentation to download a file.
<?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?
Using 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');
?>
Once you have your SFTP connection open, you can read files and write using standard PHP functions such as fopen, fread, and fwrite. You just need to use the ssh2.sftp://
resource handler to open your remote file.
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);
}
精彩评论