Open menu

Learn

PHP SFTP without SSH2

To perform SFTP operations in PHP without using the SSH2 extension, you can use phpseclib , an external library. phpseclib is a set of PHP classes that provide a pure PHP implementation of various network protocols, which allows you to perform SFTP and other operations. Before proceeding with this tutorial, make sure you have installed the phpseclib package using Composer:
composer require phpseclib/phpseclib:~3.0
Here's a basic example of how you might use phpseclib for SFTP:
require_once('vendor/autoload.php');
use phpseclib3\Net\SFTP;

// The credentials of the SFTP server
$host = 'hostname';
$user = 'username';
$password = 'password';

// Establish the connection
$sftp = new SFTP($host);
$sftp->login($user, $password);

// Loop through the files and show the file name on a new line
foreach ($sftp->nlist() as $key => $fileName) {
  echo $fileName . PHP_EOL;
}

// Get the contents of a file
echo $sftp->get('filename');

// Put contents of a file
$sftp->put('remote_file', 'local_file_content');

// Delete file
$sftp->delete('filename');
In this example, hostname , username , password , filename and remote_file are placeholders. You should replace them with your actual SFTP server's details. Remember to always secure your credentials and don't hardcode them into your scripts.