What are the best practices for sending commands to a remote shell using PHP?

When sending commands to a remote shell using PHP, it is important to ensure that the connection is secure and that the commands are executed properly on the remote server. One of the best practices is to use SSH (Secure Shell) to establish a secure connection to the remote server and then execute commands using the SSH2 functions in PHP.

// Establish SSH connection
$connection = ssh2_connect('remote_server', 22);
ssh2_auth_password($connection, 'username', 'password');

// Execute command on remote shell
$stream = ssh2_exec($connection, 'ls -la');
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);

// Close SSH connection
fclose($stream);