googleads
Read and Download Files over SFTP using PHP and ssh2 | Hire PHP
preloder
Technical

Read and Download Files over SFTP using PHP and ssh2

In one of my project, there came a situation where I was needed to download files over SFTP.  After quick google searches and going through many resources, I learned it. From my learnings, I have written this article and explained the process in simple steps so that the fellow developers can get benefited.

Here I am going to guide how to connect SFTP server using PHP ssh2 extension. I have learned it from PHP Manual. PHP manual is having many functions in ssh2 extension, here I am going to use only a few functions to connect the SFTP server, then to read the file data from remote and also download the remote file to our local machine.

                             Image source: diconnect.portal.dicentral.com

Basic Requirements:

Before using ssh2 functions you must check the phpinfo to check whether the ssh2 extension installed. Here the steps to install ssh2 via terminal

 

After successful installation run the command

 

you should see ssh2, if you are using apache, run the below command to restart the apache server

 

if you are using nginx run the below command to restart the nginx server

 

and restart the php5-fpm

sudo service php5-fpm restart

now you can see the phpinfo will show the ssh2 extension enabled.

Code:

Use the  below code to read the remote file using PHP ssh2:

 

Use the below code to download file from SFTP using PHP ssh2:

 

Explanation:

ssh2_connect – Used to establish a connection to a remote SSH server. Once established the connection we need to then authenticate using either password or public key, here i am using plain password method.

ssh2_auth_password – Used to authenticate the SFTP with the plain password.

ssh2_sftp  – Used to request the SFTP subsystem from an already connected SSH2 server.

fopen – Used to open the remote file.

stream_get_contents – Used to read all the contents inside the remote file.

ssh2_scp_recv – Used to copy a file from the remote server to the local filesystem using the SCP protocol.

Conclusion:

This a sample example for reading the content of the remote file, printing it on the browser screen, and downloading the remote file into our machine. Hope this article helped you. To keep yourself updated on new things in web development follow us. Our team at agira technologies constantly learn and adopt new things for our projects. 

The following two tabs change content below.

Vignesh Thandapani

An enthusiastic Tech Lead with 6 plus years of experience in Web development arena. Owns legitimate experience in CorePHP, Laravel, Symfony, CakePHP, Wordpress, Joomla. Behalf, a young Aspiring "Travel admirer" craves to live with Nature.

Leave a Reply

Your email address will not be published. Required fields are marked *

[contact-form-7 id="120788" title="Web Page Form"]

Schedule Your Call