Search code examples
phpsshcommand-line-interfacestty

Determining Terminal lines/cols via PHP CLI


I know that it is quite easy to figure out a terminal's size parameters via the stty -a command. When using local CLI PHP scripts, there is no problem at all on grabbing that output via system() or so.

But I am trying the same thing via a php script started from an ssh command. Sadly, all that stty ever returns is:

stty: standard input: Invalid argument.

The calling code is:

exec('stty -a | head -n 1', $query);
echo $query[0];

So the question is: If I can output to the terminal and read input from it (e.g. can fread() from STDIN and fwrite() to STDOUT in PHP, shouldn't stty also have valid STDIN and STDOUT?


Solution

  • Use ssh -t:

    % php ~/src/termtest.php
    speed 9600 baud; 39 rows; 127 columns;
    % ssh localhost php ~/src/termtest.php
    stty: stdin isn't a terminal
    % ssh -t localhost php ~/src/termtest.php
    speed 9600 baud; 39 rows; 127 columns;Connection to localhost closed.
    

    SSH does not pass in a fully functional terminal by default. Shells and ncurses seem to be able to get them somehow, but to launch something that needs one directly from SSH you need to set -t.

    For the same reason you can e.g. launch tmux (or screen) by ssh'ing to a server and then typing tmux at the prompt or through ssh -t _server_ tmux but not through sh _server_ tmux.