Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Launch PHP Websites and Applications in seconds through our 1-Click App Install Launch Now!

How to Connect to SFTP With phpseclib in Symfony 3

Updated on February 21, 2017

6 Min Read
Reading Time: 6 minutes

FTP is still the dominant manner of transferring files between servers. A more secure version of the FTP protocol, SFTP, was introduced to ensure the security of the file transfer processes. PHP offered specific functions such as ssh2_sftp for working with PHP SFTP.

Security experts have recently detected serious problems in these functions and recommend that the developers should avoid these functions for secure file transfer. Fortunately, a more secure and reliable library named PHPSeclib, is now available for working with PHP SFTP servers. Using SFTP with phpseclib results in a more secure and reliable connection that could be easily used for file transfer and related operations on any PHP web hosting.

phpseclib

In this article, I will describe how you could set up phpseclib SFTP in Symfony and then demonstrate how you could create a secure FTP function and create, update, delete and upload files to live PHP SFTP servers.

For the purpose of this article, I assume that you have already installed Symfony 3. If not, check out how to install Symfony 3 in easy steps.

Related: How To Upgrade From Symfony 2.X To 3.X

Install phpseclib in Symfony

phpseclib is a secure communication library that is very compatible with the latest PHP versions. It is available as an independent package that can be integrated within Symfony through a simple installation. You can install phpseclib using Composer.

Simply go to your project folder and run the following command:

$ composer require phpseclib/phpseclib

This command will install the latest version of phpseclib in the vendor folder of Symfony project.

Since Cloudways offers pre-integrated composer, phpseclib could be easily set up. The recommended practice is to install this PHP SFTP library throughcomposer.json.

Open composer.json in your prefered editor and add the following code:

{
   "require": {

       "phpseclib/phpseclib": "^2.0"
   }
}

Now run composer install to install it.

Now that phpseclib is installed, I will now login to my PHP SFTP server via the Master Credentials (available in the Access Details tab).

Login to the PHP SFTP Server

For PHP SFTP server login, I will use the `defaultController.php` file.

I will initialize the phpseclib library by adding the following line near the top of the file:

use phpseclib\Net\SFTP;

Now add the following code in the `indexAction()` method of the class `DefaultController`.

$sftp = new SFTP('46.xxxx.5.xxxxx');

$sftp_login = $sftp->login('master_xxxxxxekh', 'fxxxxxh6');

Verify the success of the login by getting the home URL of the server. For this, I will pass a variable in test.html.twig file (available in the views folder). Following is the complete code of the method:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;

use phpseclib\Net\SFTP;

class DefaultController extends Controller
{
   /**

    * @Route("/", name="homepage")

    */

   public function indexAction(Request $request)

   {

$sftp = new SFTP('46.xxxx.5.23xx');
$sftp_login = $sftp->login('master_xjxxxxqsxxxh', 'f6xxxxsh6');

        if($sftp_login) {

              return $this->render('default/test.html.twig', array(
              'path' => $sftp->exec('pwd'),
       ));

       }

       else throw new \Exception('Cannot login into your server !');
   }
}

In this twig, I can print the value of the variable by adding it in between the double curly braces {{ }}. In the test.html.twig, add the following code:

{% extends 'base.html.twig' %}
{% block body %}
 {{path}}
{% endblock %}

Now running the application in the browser. The home URL of the server will be displayed.

I will now describe several file operations using phpseclib.

Directory Management

Using phpseclib, you can move into directories on the server and get the files. For this purpose,  this library provides two method `exec()` and `chdir()`. In `exec()` method, you can pass the ssh command and got the results.

I will now fetch the list of all the directories on the server:

Open `indexAction()` and add the following code:

public function indexAction(Request $request)

   {

$sftp = new SFTP('46.xxxx.5.23xx');

$sftp_login = $sftp->login('master_xjxxxxqsxxxh', 'f6xxxxsh6');

if($sftp_login){

$dir = $sftp->exec('cd applications/wnxnxrbpgf/public_html/phpsec; ls -la');

echo "<pre>";

print_r($dir);

echo "</pre>";

}

Run the application in the browser and you will get the list of all the folders on the server:

You can also get file names and information such as size, mode and permissions using chdir() method.

Add the following code in the controller:

public function indexAction(Request $request)

   {

$sftp = new SFTP('46.xxxx.5.23xx');

$sftp_login = $sftp->login('master_xjxxxxqsxxxh', 'f6xxxxsh6');

if($sftp_login){

$dir = $sftp->chdir('applications/wnxnxrbpgf/public_html/phpsec');

echo "<pre>";

print_r($sftp->nlist());

print_r($sftp->rawlist());

echo "</pre>";

}

Upon execution, all the information about the files will be displayed:

You can also get the information for individual folders and files using the following methods:

$sftp->size($dir)

$sftp->stat($dir)

$sftp->lstat($dir)

Where `$dir` is the path of the folder on the server.

Phpseclib offers two methods `mkdir()` and `rmdir()` for creating and deleting files easily.

I will now create a file in my application folder by passing the URL of the project with the directory’s name.

public function indexAction(Request $request)

   {

$sftp = new SFTP('46.xxxx.5.23xx');

$sftp_login = $sftp->login('master_xjxxxxqsxxxh', 'f6xxxxsh6');

if($sftp_login){

//create the directory

$dir = $sftp->mkdir('applications/wnxnxrbpgf/public_html/phpsec/testfolder');

//open the directory

$dir = $sftp->chdir('applications/wnxnxrbpgf/public_html/phpsec/testfolder')

//remove the directory

$dir = $sftp->rmdir('applications/wnxnxrbpgf/public_html/phpsec/testfolder');

}

Similarly, to delete a single file, use the method `$sftp->delete($filepath);` where $filepath is the complete URL of file. To delete the folder and all files in it recursively, you could use $sftp->delete($folderpath, true);

Use PHP SFTP to Upload & Download Files

Next, I will demonstrate how you can get the contents of a file or download a file from a remote server. I will use the `get()` method for this purpose:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;

use phpseclib\Net\SFTP;

class DefaultController extends Controller

{

   /**

    * @Route("/", name="homepage")

    */

   public function indexAction(Request $request)

   {

$sftp = new SFTP('46.xxxx.5.23xx');

$sftp_login = $sftp->login('master_xjxxxxqsxxxh', 'f6xxxxsh6');

if($sftp_login){

//Remote file path

$dir = 'applications/wnxnxrbpgf/public_html/phpsec/testfile.php';

//get content of remote file

$dircontent = $sftp->get($dir);

//download the file in local directory

$sftp->get($dir, 'C:/xampp/htdocs/phpsec/testfile.php');

}

 return $this->render('default/test.html.twig', [

           'content' => $dircontent

     ]);

   }

}

The above code is self-explanatory. Once executed,  you should see the downloaded file in the local project folder.

To upload a file to a live server, you need to pass the URL of the local and the remote file with the desired name in the following line of code.

$sftp->put('applications/wnxnxrbpgf/public_html/testfile.php','C:/xampp/htdocs/phpsec/testfile.php',SFTP::SOURCE_LOCAL_FILE)

Using PHP SFTP Upload For Multiple Files by Finder Component

In the case where you require PHP SFTP upload, very often you need to upload multiple files to a folder at a remote server. For this, you will need a Symfony component called finder.  

First, you need to install `finder` using Composer.

$ composer require symfony/finder

Once installed, initialize the component by adding the following line of code at the top of the `defaultController.php`

use Symfony\Component\Finder\Finder;

Now in the `indexAction()` method, instantiate the object of finder and select the folder where the files to be uploaded are located. Next, I will use two methods `getRealPath()` and `getRelativePathname()` to get the file names and the relative path. Once done, I will use  a `foreach` loop to upload all the files. Following is the complete code:

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\Finder\Finder;

use phpseclib\Net\SFTP;



class DefaultController extends Controller

{

   /**

    * @Route("/", name="homepage")

    */

   public function indexAction(Request $request)

   {

$finder = new Finder();

$finder->files()->in(__DIR__."/testfolder");

$sftp = new SFTP('46.xxxx.5.23xx');

$sftp_login = $sftp->login('master_xjxxxxqsxxxh', 'f6xxxxsh6');


if($sftp_login){

foreach ($finder as $file) {

print_r($sftp->put('/applications/wnxnxrbpgf/public_html/phpsec'.$file->getRelativePathname(),$file->getRealPath(),SFTP::SOURCE_LOCAL_FILE));

}

}

}

Final Words

In this article, I discussed how you can create a secure PHP SFTP connection with the Cloudways server and perform basic CRUD actions for files and folders. You can also try this library for your servers and extend it for your project’s purposes. Refer to official documentation of phpseclib for help. Setting up PHP SFTP with phpseclib is the best way of implementing a secure file transfer process.

If you have any query or suggestions, please leave a comment below!

Share your opinion in the comment section. COMMENT NOW

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling. You can email him at shahroze.nawaz@cloudways.com

Launch PHP websites without the worry of Server Management.

Pre-Installed Optimized Stack with Git, Composer & SSH

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

THERE’S MORE TO READ.