PHP Logophpseclib/phpseclib

phpseclib is a pure PHP SSH, SFTP, and SCP implementation, along with various cryptographic primitives (RSA, AES, TripleDES, etc.). It's a comprehensive library designed to provide robust and secure network communication and encryption capabilities entirely in PHP, without requiring any external extensions like `pecl/ssh2` or `OpenSSL` (though it can leverage OpenSSL if available for performance). This makes phpseclib highly portable and easy to deploy across different environments.

Key features and benefits:

1. Pure PHP: Eliminates the need for compiling or installing C extensions, simplifying deployment and ensuring cross-platform compatibility.
2. SSH2 Client: Allows PHP applications to connect to remote servers over SSH, execute commands, retrieve output, and manage tunnels.
3. SFTP Client: Provides secure file transfer capabilities, including uploading, downloading, listing directories, and managing permissions over SFTP.
4. SCP Client: Offers a simpler secure copy protocol for file transfers.
5. Cryptographic Primitives: Includes implementations of various encryption algorithms (e.g., AES, Blowfish, TripleDES), hashing functions (e.g., SHA1, SHA256), and public-key cryptography (e.g., RSA, Diffie-Hellman). This allows for secure data handling within the PHP application itself.
6. Key Management: Supports loading and saving SSH keys (both public and private) in various formats (PKCS#1, PKCS#8, PuTTY PPK, OpenSSH).
7. Flexibility: Can be used for a wide range of tasks, from automated server management and deployment scripts to secure data exchange between applications.

Installation is typically done via Composer:
`composer require phpseclib/phpseclib:~3.0`

phpseclib is widely used in projects that require secure remote interactions or robust cryptography where external dependencies are a concern or not feasible.

Example Code

```php
<?php

require 'vendor/autoload.php';

use phpseclib3\Net\SSH2;
use phpseclib3\Crypt\RSA;

// --- SSH Connection and Command Execution Example ---

// Replace with your server details
$host = 'your_server_ip_or_hostname';
$username = 'your_username';
$password = 'your_password'; // Or use a private key for authentication

try {
    // Create a new SSH2 instance
    $ssh = new SSH2($host);
    $ssh->setTimeout(10); // Set a timeout for connection/commands (optional)

    // Attempt to log in with username and password
    if (!$ssh->login($username, $password)) {
        // --- Alternative: Login with a private key ---
        // If you're using a private key, uncomment the following lines
        // and comment out the password login block above.
        /*
        $privateKeyPath = '/path/to/your/private_key.pem'; // e.g., '~/.ssh/id_rsa'
        if (!file_exists($privateKeyPath)) {
            throw new \Exception('Private key file not found at: ' . $privateKeyPath);
        }
        $key = RSA::loadPrivateKey(file_get_contents($privateKeyPath));
        // If your private key is password-protected, set the password:
        // $key->setPassword('your_key_passphrase');

        if (!$ssh->login($username, $key)) {
            throw new \Exception('SSH Login Failed using private key. Check username, key, and passphrase.');
        }
        */
        
        throw new \Exception('SSH Login Failed using password. Check username and password.');
    }

    echo "Successfully connected to SSH server: {$host}\n\n";

    // Execute a simple command and get the output
    $command1 = 'ls -la';
    echo "Executing command: '{$command1}'\n";
    $output1 = $ssh->exec($command1);
    echo "Output:\n{$output1}\n";

    // Execute another command
    $command2 = 'hostname';
    echo "Executing command: '{$command2}'\n";
    $output2 = $ssh->exec($command2);
    echo "Output:\n{$output2}\n";

    // Check exit status of the last executed command (0 for success)
    $exitStatus = $ssh->getExitStatus();
    echo "Last command exit status: {$exitStatus}\n\n";

    // --- SFTP Example (brief) ---
    // For SFTP, you'd typically use phpseclib3\Net\SFTP class similarly
    /*
    use phpseclib3\Net\SFTP;
    $sftp = new SFTP($host);
    if ($sftp->login($username, $password)) {
        echo "SFTP Connected.\n";
        // Upload a file
        // $sftp->put('remote_file.txt', 'Hello World', SFTP::SOURCE_STRING); // Put string content
        // $sftp->put('remote_file.txt', '/path/to/local_file.txt', SFTP::SOURCE_LOCAL_FILE); // Put local file

        // Download a file content
        // $content = $sftp->get('remote_file.txt');
        // echo "Downloaded content: {$content}\n";
        
        // List directory
        // print_r($sftp->nlist('.'));

        $sftp->disconnect();
        echo "SFTP Disconnected.\n";
    } else {
        echo "SFTP Login Failed.\n";
    }
    */

    // Disconnect (optional, object will be garbage collected when script ends)
    $ssh->disconnect();
    echo "Disconnected from SSH server.\n";

} catch (\Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
    // For more detailed SSH errors if available:
    // if (isset($ssh)) {
    //     echo "SSH Last Error: " . $ssh->getLastError() . "\n";
    // }
}

?>
```