检测stdin是否是PHP中的tty设备(终端)或管道?

时间:2020-12-19 14:08:48

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.

我写了一个PHP脚本。我希望它在使用连接到tty设备(终端)的标准输入调用之前显示帮助消息,然后以交互方式读取和执行,但是在使用文件或来自管道的流作为标准输入调用时不显示。

Is there a way to detect this from PHP?

有没有办法从PHP中检测到这个?

2 个解决方案

#1


12  

Use posix_isatty.

使用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.

此函数接受文件描述符(整数)和PHP流。如果它收到PHP流,它会自动尝试转换它以获取文件描述符并使用它。

#2


0  

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

从PHP 7.2开始,您可以使用stream_isatty,它也适用于Windows。

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).

(这当然也适用于STDOUT)。

#1


12  

Use posix_isatty.

使用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.

此函数接受文件描述符(整数)和PHP流。如果它收到PHP流,它会自动尝试转换它以获取文件描述符并使用它。

#2


0  

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

从PHP 7.2开始,您可以使用stream_isatty,它也适用于Windows。

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).

(这当然也适用于STDOUT)。