How to download a file from SFTP using PHP?

I am trying to download a file from sftp server using php, but I can not find the correct documentation to download the 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 open the SFTP connection, what do I need to do to download the file?

+6
source share
2 answers

Using phpseclib, a pure implementation of 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'); ?> 
+5
source

After opening your SFTP connection, 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 the remote file.

Here is an example that scans a directory and uploads all files to 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); } 
+3
source

Source: https://habr.com/ru/post/897296/


All Articles