What are some best practices for connecting to a server using SSH2 in PHP?

When connecting to a server using SSH2 in PHP, it is important to follow best practices to ensure secure and reliable communication. This includes properly handling errors, securely storing credentials, and closing the connection when finished.

<?php

$server = 'example.com';
$port = 22;
$username = 'username';
$password = 'password';

$connection = ssh2_connect($server, $port);

if (!$connection) {
    die('Connection failed');
}

if (!ssh2_auth_password($connection, $username, $password)) {
    die('Authentication failed');
}

// Perform actions on the server

ssh2_exec($connection, 'ls -la');

// Close the connection
ssh2_disconnect($connection);

?>