PHP ssh2://

The ssh2:// wrapper in PHP provides secure access to remote resources using the libssh2 library. It enables shell access, remote execution, tunneling, file transfer, and SCP operations through cryptographic transport.

Installation Required: The SSH2 extension must be installed from PECL as it's not enabled by default in PHP.

Install using: pecl install ssh2

Available SSH2 Wrappers

PHP provides several SSH2 wrappers for different operations −

ssh2.shell://user:pass@example.com:22/xterm
ssh2.exec://user:pass@example.com:22/usr/local/bin/somecmd
ssh2.tunnel://user:pass@example.com:22/192.168.0.1:14
ssh2.sftp://user:pass@example.com:22/path/to/filename
ssh2.scp://user:pass@example.com:22/path/to/filename

Basic Example

Here's how to read a remote file using SSH2 SFTP wrapper −

<?php
// Create context with SSH2 options
$context = stream_context_create([
    'ssh2' => [
        'username' => 'myuser',
        'password' => 'mypassword'
    ]
]);

// Read remote file
$contents = file_get_contents('ssh2.sftp://example.com/path/to/file.txt', false, $context);
echo $contents;
?>

Context Options

Option Description
session Preconnected ssh2 resource to be reused
sftp Preallocated sftp resource to be reused
methods Key exchange, hostkey, cipher, compression, and MAC methods
username Username to connect as
password Password for authentication
pubkey_file Public key file path for authentication
privkey_file Private key file path for authentication
env Associative array of environment variables
term Terminal emulation type (xterm, vt102, etc.)
term_width Terminal width in characters
term_height Terminal height in characters
term_units Units for width and height (pixels or chars)

Key-Based Authentication

For enhanced security, use SSH keys instead of passwords −

<?php
$context = stream_context_create([
    'ssh2' => [
        'username' => 'myuser',
        'pubkey_file' => '/path/to/public.key',
        'privkey_file' => '/path/to/private.key'
    ]
]);

$handle = fopen('ssh2.sftp://example.com/remote/file.txt', 'r', false, $context);
?>

Conclusion

SSH2 wrappers provide a convenient way to access remote resources securely in PHP. They support various authentication methods and can be used with standard PHP file functions for seamless remote operations.

Updated on: 2026-03-15T09:27:44+05:30

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements