If the ssh2_exec takes awhile to run, and you need a handshake, you can use a file. In this case, $flag names a handshake file that is written when the ssh script finishes.
<?php
$stream = ssh2_exec($connection, $command . " $public_key $private_key;");
$i=0;
while (!file_exists ($flag) && ($i < MAX_TIME))
{
sleep(1);
$i++;
}
$ret_val=($stream!=FALSE);
?>
This is an extract out of the bash script that is running. Be sure to allow the webserver permission to read the file that the script writes.
echo 0 > $OUTFILE
chmod 666 $OUTFILE
One other note: you can put more than one command in by separating them with ';' (semicolons).