Manual installation of phpseclib

February 11, 2019

When you need to connect to a secure ftp server (SFTP), the first solution that will come to your mind is to use the ssh2 php library, which is included by default on any php installation.

However, usually is not the last version of ssh2 the one that comes installed with php.

So it happened to me, that on a recent project requiring to connect to a secure ftp server (SFTP), the following error kept appearing no matter what I tried.

Warning: ssh2_connect(): Error starting up SSH connection(-5): Unable to exchange encryption keys in <source-file> on line <line-no>

Warning: ssh2_connect(): Unable to connect to <server-name> in <source-file> on line <line-no>

The problem was, as I found later, that the SFTP server seemed to be running newer version of encryption algorithms that were not implemented on the ssh2 library I was using.


The solution was on the phpseclib library, which is a complete and pure-php implementation system -- that allows to use SSH, SFTP -- and hence doesn't have any dependency on other libraries running on the server.

The installation method described on the official phpseclib page indicates to use composer. However sometimes we don't have access to it, such as in virtual hosts, or just simply because we prefer not to use it.

What we can do instead, is a manual installation.

At the time of this writing, the latest stable version is 2.0 which can accessed through their GitHub page.
Then we proceed first by opening the page on our favorite browser.

Once we have opened the github page, we will find a "Branches" drop-down where we will select the version 2.0.
Then we can proceed to click on the "Clone or Download" button, and select the "Download Zip" option.

Unzip the downloaded files. You will find a phpseclib folder that would need to be placed on your project folder.

  (your files)

Then, in our scripts we have to add the location of the phpseclib library to the "include path", and we have to manually include the files we need. (As shown on the source examples below)

For instance, a script to login, to a SFTP server, with an user and password would require the Net/SSH2.php and Net/SFTP.php files.

Another script, that will login, to a SFTP server, with a private key, will additionally require the Crypt/RSA.php, Math/BigInteger.php, and Crypt/Hash.php files.

And when you need to perform additional SFTP operations, you would need to include additional files such as shown in the code below.