PHP Master | Using SSH and SFTP with PHP (2024)

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 filessh2_scp_send($conn, '/local/filename', '/remote/filename', 0644);// fetch filessh2_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 folderssh2_sftp_mkdir($sftp, '/home/username/newdir');// Rename the folderssh2_sftp_rename($sftp, '/home/username/newdir', '/home/username/newnamedir');// Remove the new folderssh2_sftp_rmdir($sftp, '/home/username/newnamedir');// Create a symbolic linkssh2_sftp_symlink($sftp, '/home/username/myfile', '/var/www/myfile');// Remove a filessh2_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 foldermkdir('ssh2.sftp://' . $sftp . '/home/username/newdir');// Remove the new folderrmdir('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.

<?phpclass SSH2Authentication{}
<?phpclass 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.

<?phpclass 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.

<?phpclass 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.

<?phpclass 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 SCPif ($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 SFTPif ($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');
}

PHP Master | Using SSH and SFTP with PHP (2024)

References

Top Articles
The 7 Best Granular Weed Killers
Best Pet-Safe Weed Killers That Actually Work to Banish Weeds and Grass
11 beste sites voor Word-labelsjablonen (2024) [GRATIS]
Www.1Tamilmv.cafe
Zabor Funeral Home Inc
J & D E-Gitarre 905 HSS Bat Mark Goth Black bei uns günstig einkaufen
Research Tome Neltharus
Plaza Nails Clifton
Self-guided tour (for students) – Teaching & Learning Support
Rochester Ny Missed Connections
Bed Bath And Body Works Hiring
Best Restaurants In Seaside Heights Nj
Craigslist Estate Sales Tucson
My.doculivery.com/Crowncork
Meritas Health Patient Portal
Shreveport Active 911
Dit is hoe de 130 nieuwe dubbele -deckers -treinen voor het land eruit zien
Christina Khalil Forum
Mineral Wells Independent School District
Finger Lakes Ny Craigslist
10-Day Weather Forecast for Santa Cruz, CA - The Weather Channel | weather.com
Robin D Bullock Family Photos
Lakers Game Summary
Bible Gateway passage: Revelation 3 - New Living Translation
Www.craigslist.com Savannah Ga
Kentuky Fried Chicken Near Me
Avatar: The Way Of Water Showtimes Near Maya Pittsburg Cinemas
Kimoriiii Fansly
TJ Maxx‘s Top 12 Competitors: An Expert Analysis - Marketing Scoop
Osrs Important Letter
Life Insurance Policies | New York Life
Mumu Player Pokemon Go
Pch Sunken Treasures
Los Amigos Taquería Kalona Menu
Dumb Money, la recensione: Paul Dano e quel film biografico sul caso GameStop
B.k. Miller Chitterlings
Dreammarriage.com Login
2016 Honda Accord Belt Diagram
Panchitos Harlingen Tx
The 50 Best Albums of 2023
Wlds Obits
968 woorden beginnen met kruis
The All-New MyUMobile App - Support | U Mobile
Firestone Batteries Prices
Traumasoft Butler
Craigslist/Nashville
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
Heat Wave and Summer Temperature Data for Oklahoma City, Oklahoma
Grandma's Portuguese Sweet Bread Recipe Made from Scratch
Ssss Steakhouse Menu
Kobe Express Bayside Lakes Photos
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6122

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.