ssh tunnel to database

juergen_mueller

DaDaBIK Guru
Hi

I would like (because I would need it for a specific reason) to establish a database connection via a SSH tunnel. Is this possible with DaDaBik, generally speaking?

I have this code generated by ChatGPT. Will this work ?

Code:
<?php
// SSH server credentials
$ssh_host = 'your_ssh_host'; // SSH server hostname or IP address
$ssh_port = 22; // SSH port
$ssh_username = 'your_ssh_username'; // SSH username
$ssh_password = 'your_ssh_password'; // SSH password

// Database server credentials
$db_host = 'localhost'; // Database server hostname or IP address (localhost if tunneled)
$db_port = 3306; // Database port
$db_username = 'your_db_username'; // Database username
$db_password = 'your_db_password'; // Database password
$db_name = 'your_db_name'; // Database name

// SSH tunnel parameters
$local_port = 3307; // Local port for tunnel
$remote_host = '127.0.0.1'; // Remote host (database server) accessible through the SSH tunnel
$remote_port = 3306; // Remote port (database port)

// Establish SSH connection
$connection = ssh2_connect($ssh_host, $ssh_port);
if (!$connection) {
    die('SSH connection failed.');
}

// Authenticate with SSH credentials
if (!ssh2_auth_password($connection, $ssh_username, $ssh_password)) {
    die('SSH authentication failed.');
}

// Open SSH tunnel
$ssh_tunnel = ssh2_tunnel($connection, $remote_host, $remote_port, $local_port);
if (!$ssh_tunnel) {
    die('SSH tunnel failed.');
}

// Establish database connection via SSH tunnel
$db_connection = new mysqli('127.0.0.1', $db_username, $db_password, $db_name, $local_port);
if ($db_connection->connect_error) {
    die('Database connection failed: ' . $db_connection->connect_error);
}

echo 'Connected to database successfully!';

// Now you can execute database queries using $db_connection

// Don't forget to close connections when done
$db_connection->close();
ssh2_disconnect($connection);
?>

Thanks,

Juergen
 

eugenio

Administrator
Staff member
Hi Juergen,
honestly I have never used the ssh2_tunnel PHP function so I can't say for sure if this will work.
Was the idea to add the code to the startup function? If this is the case, the problem is that the startup function is called after the db connection. If you are ok with editing /include/db_functions.php, you could change connect_db() to make a MySQL connection over SSL (you can easily find examples online); soon, I would like to implement DB SSL connection as a built-in feature.

Best,
 
Top