Using SSH and SFTP with PHP

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.
yum install php-pecl-ssh2

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, array('hostkey'=>'ssh-rsa'));
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 futuressh2_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.

 

Using phpseclib

There is another option which is using phpseclib library

To authenticate:

 

include('Net/SFTP.php');
//connect to the server
$sftp = new Net_SFTP('example.com');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}

 

To authenticate using public key:

include('Net/SFTP.php'); include('Crypt/RSA.php'); $sftp = new Net_SFTP('example.com'); $key = new Crypt_RSA(); $key->loadKey(file_get_contents('/root/.ssh/id_rsa')); if (!$sftp->login('username', $key)) { exit('Login Failed'); }

Getting file using SFTP:

// outputs the contents of filename.remote to the screen
echo $sftp->get('filename.remote');
// copies filename.remote to filename.local from the SFTP server
$sftp->get('filename.remote', 'filename.local');

// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
// puts an x-byte file named filename.remote on the SFTP server,
// where x is the size of filename.local
$sftp->put('filename.remote', 'filename.local', NET_SFTP_LOCAL_FILE);

Leave a Comment.