How can you ensure proper communication between PHP and an external program when using ssh2_exec?

When using ssh2_exec to run an external program from PHP, it is important to properly manage the input and output streams to ensure proper communication between the two. One way to do this is by using stream functions to read and write data between PHP and the external program.

$connection = ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

$stream = ssh2_exec($connection, '/path/to/external/program');
stream_set_blocking($stream, true);

fwrite($stream, "input data\n");

$output = stream_get_contents($stream);

fclose($stream);

echo $output;