Are there alternative methods to using shell_exec in PHP for executing commands on a remote server?

Using shell_exec in PHP to execute commands on a remote server can pose security risks and may not be the best practice. Instead, consider using secure alternatives such as SSH2 or PHP's built-in functions like curl or fopen to interact with remote servers in a safer manner.

// Example using SSH2 to execute commands on a remote server
$connection = ssh2_connect('remote-server-ip', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, 'ls -la');
stream_set_blocking($stream, true);
$data = '';
while ($buffer = fread($stream, 4096)) {
    $data .= $buffer;
}
fclose($stream);

echo $data;