Using SSH and SFTP with PHP

In today’s world with so many third-party integrations and content-sharing, it’s important to understand and make use of protocols like SCP and SFTP. PHP’s SSH2 extension, a wrapper for libssh2 which implements the SSH2 protocol, provides several functions you can use to securely transfer files.

To begin leveraging these functions, it’s obvious the SSH2 package needs to be installed. As it’s a PECL extension, the installation process will depend based on your operating system of choice. Follow the guidelines on php.net.

Establishing a Connection

Let’s begin by connecting to an SSH service. Establishing a connection is as simple as:

<?php
$conn = ssh2_connect('example.com', 22);
ssh2_auth_password($conn, 'username', 'password');

Some administrators prefer using public and private keys to authenticate logins. If the service is configured and you want to connect in this way, you would use the following instead:

<?php
$conn = ssh2_connect('example.com', 22);
ssh2_auth_pubkey_file(
    $conn,
    'username',
    '/home/username/.ssh/id_rsa.pub',
    '/home/username/.ssh/id_rsa'
);

Whether you use username/password or public/private key authentication, ssh2_auth_password() and ssh2_auth_pubkey_file() both return a Boolean value indicating whether authentication was successful.

Performing Basic Commands

Once you have successfully authenticated with the server, you can perform your file transfer operations. The SCP functions let you send or receive a file(s) like so:

<?php
// send a file
ssh2_scp_send($conn, '/local/filename', '/remote/filename', 0644);

// fetch file
ssh2_scp_recv($conn, '/remote/filename', '/local/filename');

ssh2_scp_send() has an additional parameter which you can specify what the file permission should be on the remote server when the file is copied.

More functionality is available with the SFTP functions; you can change file or directory permissions, fetch information about a file, create directories, rename items, remove items, etc. They work quite similar to the SCP functions above, but an additional connect via ssh2_sftp() must be made prior to using the functions:

<?php
$sftp = ssh2_sftp($conn);

// Create a new folder
ssh2_sftp_mkdir($sftp, '/home/username/newdir');

// Rename the folder
ssh2_sftp_rename($sftp, '/home/username/newdir', '/home/username/newnamedir');

// Remove the new folder
ssh2_sftp_rmdir($sftp, '/home/username/newnamedir');

// Create a symbolic link
ssh2_sftp_symlink($sftp, '/home/username/myfile', '/var/www/myfile');

// Remove a file
ssh2_sftp_unlink($sftp, '/home/username/myfile');

ssh2_sftp() accepts the connection resource and returns an SFTP resource which is used in future ssh2_sftp_* calls. The calls then return a Boolean which allows you to determine whether the action was successful.

Using Wrapper Functions

When a specific file management function doesn’t exist for SFTP or SCP, generally the core file system function will work using a stream wrapper. Below are a few examples:

<?php
// Create a new folder
mkdir('ssh2.sftp://' . $sftp . '/home/username/newdir');

// Remove the new folder
rmdir('ssh2.sftp://' . $sftp . '/home/username/newdir');

// Retrieve a list of files
$files = scandir('ssh2.sftp://' . $sftp . '/home/username');

Before performing any of these calls, the connection to the SSH and SFTP server must be made as it uses the previously created $sftp variable.

Bring It All Together

Now that you are able to connect, authenticate, and run commands on an SSH server, we can create a few helper classes to simplify the process of executing these commands: one for performing SCP calls and one for SFTP calls, a parent class for common functionality, and a couple classes for encapsulating authentication information (password and keys).

Let’s create the authentication classes first since they will be used the other classes.

<?php
class SSH2Authentication
{
}
<?php
class SSH2Password extends SSH2Authentication
{
    protected $username;
    protected $password;

    public function __construct($username, $password) {
        $this->username = $username;
        $this->password = $password;
    }

    public function getUsername() {
        return $this->username;
    }

    public function getPassword() {
        return $this->password;
    }
}
<?
class SSH2Key extends SSH2Authentication
{
    protected $username;
    protected $publicKey;
    protected $privateKey;

    public function __construct($username, $publicKey, $privateKey) {
        $this->username = $username;
        $this->password = $password;
    }

    public function getUsername() {
        return $this->username;
    }

    public function getPublicKey() {
        return $this->publicKey;
    }

    public function getPrivateKey() {
        return $this->privateKey;
    }
}

SSH2Password and SSH2Key simply wrap their respective authentication information. They share a common base class so we can take advantage of PHP’s type hinting when we pass instances to their consumers.

Moving on, let’s create an SSH2 to connect and authenticate with the SSH server.

<?php
class SSH2
{
    protected $conn;

    public function __construct($host, SSH2Authentication $auth, $port = 22) {
        $this->conn = ssh2_connect($host, $port);
        switch(get_class($auth)) {
            case 'SSH2Password':
                $username = $auth->getUsername();
                $password = $auth->getPassword();
                if (ssh2_auth_password($this->conn, $username, $password) === false) {
                    throw new Exception('SSH2 login is invalid');
                }
                break;
            case 'SSH2Key':
                $username = $auth->getUsername();
                $publicKey = $auth->getPublicKey();
                $privateKey = $auth->getPrivateKey();
                if (ssh2_auth_pubkey_file($this->conn, $username, $publicKey, $privateKey) === false) {
                    throw new Exception('SSH2 login is invalid');
                }
                break;
            default:
                throw new Exception('Unknown SSH2 login type');
        }
    }
}

A very simple SCP class will be created that extends SSH2 and will make use of the magic method __call(). This allows us to do two important things: automatically prepend “ssh_scp_” to the function call and supply the connection variable to the call.

<?php
class SSH2SCP extends SSH2
{
    public function __call($func, $args) {
        $func = 'ssh2_scp_' . $func;
        if (function_exists($func)) {
            array_unshift($args, $this->conn);
            return call_user_func_array($func, $args);
        }
        else {
            throw new Exception(
                $func . ' is not a valid SCP function');
        }
    }
}

The SFTP class is quite similar, although its constructor is overloaded to also execute the ssh2_sftp() function. The results are stored in a protected variable and automatically prepended to all SFTP function calls.

<?php
class SSH2SFTP extends SSH2 {
    protected $sftp;

    public function __construct($host, ISSH2Authentication $auth, $port = 22) {
        parent::__construct($host, $auth, $port);
        $this->sftp = ssh2_ftp($this->conn);
    }
    public function __call($func, $args) {
        $func = 'ssh2_sftp_' . $func;
        if (function_exists($func)) {
            array_unshift($args, $this->sftp);
            return call_user_func_array($func, $args);
        }
        else {
            throw new Exception(
                $func . ' is not a valid SFTP function');
        }
    }
}

Once these classes are created they can be used to execute SCP and SFTP function calls. Thanks to the useful __call methods in both classes, we don’t need to pass the open connection or repeatedly type “ssh2_scp_” or “ssh2_ftp_” with each call.

<?php
// Create SCP connection using a username and password
$scp = new SCP(
    'example.com',
    new SSH2Password('username', 'password')
);
// Receive a file via SCP
if ($scp->recv('remote/file', 'local/file')) {
    echo 'Successfully received file';
}

// Create SFTP connection using a public/private key
$sftp = new SSH2SFTP(
    'example.com',
    new SSH2Key('username', 'public_key', 'private_key')
);
// Create a directory via SFTP
if ($sftp->mkdir('directory/name')) {
    echo 'Successfully created directory';
} 

Summary

Installing the SSH2 PHP extension, it provides your scripts with the ability to connect to SSH2 servers. You can either leverage the handy classes that simplify the code for performing SFTP or SCP calls, or if a specific function isn’t provided by the library, most core file system operations can be used by leveraging the SSH2 wrapper functionality.

Image via Fotolia

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • lingtalfi

    woa, php is so powerful !

  • http://davidreagan.net David R

    How would you run a system command. Like cd’ing into a directory and tarball’ing all the files in it.

    This function? http://php.net/manual/en/function.ssh2-exec.php

  • http://magnetikonline.com.au/ Peter Mescalchin

    Nice introduction to SSH functions under PHP5. (Warning: self promotion here). Have recently used this extension for a handy little PHP CLI utility for diffing production file system config files/etc.

    https://github.com/magnetikonline/sshdiff

  • againstallodds

    I prefer phpseclilb, a pure PHP SSH / SFTP implementation, myself: http://phpseclib.sourceforge.net/

    There are several problems with the solution your proposing in my opinion. The biggest problem is that your solution is non-portable. Most hosts don’t have PHP’s SSH2 extension installed. And even if they do…

    PHP’s SSH2 extension requires the private key and the public key both live on the filesystem. phpseclib accepts the key as a string and only needs the private key – not the public key (the public key can usually be extracted from the private key).

    phpseclib supports keyboard-interactive authentication, as well, and is overall more reliable. With PHP’s SSH2 extension, you do ssh2_exec and you may get ANSI escape codes back. phpseclib doesn’t do this unless you’re using the interactive read() / write(). Which, right there, is another advantage phpseclib has over PHP’s SSH2 extension – interactive mode.

    Plus, surprisingly, phpseclib is faster, too.

    Anyway just my two cents. Check phpseclib out: http://phpseclib.sourceforge.net/

  • Shay

    Should the SSH2Key class use $privateKey and not $password above?