Using SSH and SFTP with PHP

Share this article

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

Frequently Asked Questions (FAQs) on Using SSH and SFTP with PHP

What is the difference between SSH and SFTP in PHP?

SSH (Secure Shell) and SFTP (SSH File Transfer Protocol) are both protocols used for secure data transfer over the internet. SSH is a network protocol that provides a secure way to access a remote computer. It provides strong password authentication and public key authentication, as well as encrypted data communication between two computers connected over the internet. On the other hand, SFTP is a secure file transfer protocol that provides file access, file transfer, and file management functionalities over any reliable data stream. It is typically used with the SSH-2 protocol to provide secure file transfer.

How can I connect to an SFTP server using PHP?

To connect to an SFTP server using PHP, you can use the ssh2_sftp function. This function allows you to establish an SFTP session over an already established SSH connection. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
$stream = fopen("ssh2.sftp://$sftp/path/to/file", 'r');
} else {
die('Authentication failed');
}

How can I upload a file to an SFTP server using PHP?

To upload a file to an SFTP server using PHP, you can use the ssh2_scp_send function. This function allows you to upload a file to a remote server over an established SSH connection. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
} else {
die('Authentication failed');
}

How can I download a file from an SFTP server using PHP?

To download a file from an SFTP server using PHP, you can use the ssh2_scp_recv function. This function allows you to download a file from a remote server over an established SSH connection. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
ssh2_scp_recv($connection, '/remote/filename', '/local/filename');
} else {
die('Authentication failed');
}

How can I list all files in a directory on an SFTP server using PHP?

To list all files in a directory on an SFTP server using PHP, you can use the ssh2_sftp function in combination with the scandir function. Here is a basic example of how you can use these functions:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
$dir = "ssh2.sftp://$sftp/path/to/directory";
$files = scandir($dir);
print_r($files);
} else {
die('Authentication failed');
}

How can I delete a file on an SFTP server using PHP?

To delete a file on an SFTP server using PHP, you can use the ssh2_sftp_unlink function. This function allows you to delete a file on a remote server over an established SFTP session. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
ssh2_sftp_unlink($sftp, '/path/to/file');
} else {
die('Authentication failed');
}

How can I create a directory on an SFTP server using PHP?

To create a directory on an SFTP server using PHP, you can use the ssh2_sftp_mkdir function. This function allows you to create a directory on a remote server over an established SFTP session. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
ssh2_sftp_mkdir($sftp, '/path/to/directory');
} else {
die('Authentication failed');
}

How can I delete a directory on an SFTP server using PHP?

To delete a directory on an SFTP server using PHP, you can use the ssh2_sftp_rmdir function. This function allows you to delete a directory on a remote server over an established SFTP session. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
ssh2_sftp_rmdir($sftp, '/path/to/directory');
} else {
die('Authentication failed');
}

How can I rename a file on an SFTP server using PHP?

To rename a file on an SFTP server using PHP, you can use the ssh2_sftp_rename function. This function allows you to rename a file on a remote server over an established SFTP session. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
ssh2_sftp_rename($sftp, '/path/to/oldname', '/path/to/newname');
} else {
die('Authentication failed');
}

How can I change the permissions of a file on an SFTP server using PHP?

To change the permissions of a file on an SFTP server using PHP, you can use the ssh2_sftp_chmod function. This function allows you to change the permissions of a file on a remote server over an established SFTP session. Here is a basic example of how you can use this function:

$connection = ssh2_connect('hostname', 22);
if (ssh2_auth_password($connection, 'username', 'password')) {
$sftp = ssh2_sftp($connection);
ssh2_sftp_chmod($sftp, '/path/to/file', 0644);
} else {
die('Authentication failed');
}

Jamie MunroJamie Munro
View Author

Jamie Munro is the author of Rapid Application Development with CakePHP, 20 Recipes for Programming MVC 3, and most recently 20 Recipes for Programming PhoneGap - all books are available in print and electronic format.

Advanced
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week