PHP code example of kanti / ssh-tunnel

1. Go to this page and download the library: Download kanti/ssh-tunnel library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kanti / ssh-tunnel example snippets


$tunnel = new \Kanti\SshTunnel\SshTunnel(
    sshHost: "testServer", // uses the default ssh config ~/.ssh/config
    remote: \Kanti\SshTunnel\Remote::tcp(3306, '127.0.0.1'),
    localPort: null, // if empty will auto select a local port for you (recommended)
);
$localPort = $tunnel->start();
$connection = new \PDO('mysql:host=127.0.0.1;port=' . $localPort, 'user', 'password');

$tunnel = new \Kanti\SshTunnel\SshTunnel(
    sshHost: "testServer", // uses the default ssh config ~/.ssh/config
    remote: \Kanti\SshTunnel\Remote::socket('/var/run/mysqld/mysqld.sock'), // can also expose the mysql socket as tcp port.
    localPort: null,
);
$localPort = $tunnel->start();
$connection = new \PDO('mysql:host=127.0.0.1;port=' . $localPort, 'user', 'password');

use \Kanti\SshTunnel\SshTunnel;

// tunnel to connect to a remote MySQL server
$tunnel = new SshTunnel(
    // set custom ssh settings:
    sshUser: 'user',
    sshHost: "1.1.1.1",
    sshPort: 221,
    remote: \Kanti\SshTunnel\Remote::tcp(3306, '192.168.0.2'),
    localPort: null,
);
$localPort = $tunnel->start();

// connect to mysql
$connection = new \PDO('mysql:host=127.0.0.1;port=' . $localPort, 'user', 'password');

// do something with the connection

$tunnel->stop(); // stops the tunnel
// OR 
unset($tunnel); // also stops the tunnel (can be disabled in the constructor disconnectAfterTunnelDestroyed: false)
// OR
// you can stop the PHP Script, that will also stop the tunnel (via inactivity timeout)

made with ❤️ by Kanti (Matthias Vogel)