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