Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if stdin is a tty device (terminal) or pipe in PHP?

I wrote a php script. I want it show help message when called with standard input connected to a tty device (terminal) before reading and executing interactively, but dont show when called with a file or stream from pipe as standard input.

Is there a way to detect this from PHP?

like image 633
Cofyc Avatar asked Sep 06 '10 03:09

Cofyc


2 Answers

Use posix_isatty.

This function accepts both a file descriptor (an integer) and a PHP stream. If it receives a PHP stream, it automatically attempts to cast it in order to obtain a file descriptor and use it instead.

like image 198
Edward Z. Yang Avatar answered Oct 05 '22 07:10

Edward Z. Yang


Since PHP 7.2 you can use stream_isatty, which works on Windows too.

For example:

php -r "var_dump(stream_isatty(STDERR));"

Results in

bool(true)

But

php -r "var_dump(stream_isatty(STDERR));" 2>output.txt

Results in

bool(false)

(this of course works on STDOUT too).

like image 22
Michele Locati Avatar answered Oct 05 '22 07:10

Michele Locati