To run a shell script with all the variables that you would have when logged in interactively add bash -l or sh --login infront of your command. The script I use creates a shell script, copies the script to the box with ssh2_scp_send, then executes the script with ssh2_exec. Hope this helps somebody.

Keep in mind that when using ssh2_shell, the remote system's EOL may not be the same as PHP's EOL, so it may not be safe to use PHP_EOL. The native EOL for Windows is \r\n, while Unix is typically merely \n, and classic Mac for some reason is \r.

If you're running PHP on Windows (\r\n) and sshing into a Unix box (\n) you're going to end up sending extra lines. My experience so far is that it just acts as though you typed nothing, which may cause issues with password prompts.

we could also use shell_exec to execute multiple related commandsseparated by semicolon (;).

And I figured out problem that sometimes arise related to the execution of complex java c/c++ programs. All we need to do is to set the required environment variables. I have a environment variable in .bash_profile. This variable would be set when I log into my account normally through shell. But when we use ssh2_connect(), the environment variables in the .bash_profile are not set, all we need to do is export the required environment variables with shell_exec();

Instead of using sleep(1) try using usleep(350000). If not, you will need to spend much time unnecessary. In my scripts, I tried to use usleep(250000), but it's too short and brought some problems. usleep(300000) worked, but only to garantee use 350000. ;)

In my case the ssh2_shell doesn't work every time. There were many problems:- If I use stream_get_contents, the command(s) never executed- with while ($buf = fgets...) the loop never stops- without sleep(1) before stream_set_blocking, the command wasn't execute every time. Anyone knows why?That's what I made, and it works - but I think it isn't what it should be:<?php $strCommand = 'tar -C /path/to/extract -xjf /path/from/file.tar.bz2';$sshStream = ssh2_shell($this->sshSession, 'xterm', null, 120, 24, SSH2_TERM_UNIT_CHARS); fwrite($sshStream, $strCommand . PHP_EOL);sleep(1);stream_set_blocking($sshStream, true);$sshUntarRetval = ""; while ($buf = fgets($sshStream,4096)) {flush();$sshUntarRetval .= $buf; if (strpos($buf, 'tar -C') !== false) { break; } }fclose($sshStream);?>