I am wondering what is the difference between stream_isatty and posix_isatty. I have also gone through with the documentation part for both as below:
stream_isatty: https://www.php.net/manual/en/function.stream-isatty.php
posix_isatty: https://www.php.net/manual/en/function.posix-isatty.php
But unable to get the exact usages and differences between both of them. Can someone please help in understanding the same with an example if possible?
Thanks in advance
As commented by KIKO Software
and Ken Lee, the main differences are that stream_isatty()
supports Microsoft Windows
and posix_isatty()
allows passing a file-descriptor (integer) next to a stream handle.
You asked for an example, here is one for using an integer as a parameter. It highlights a difference between the two functions:
PHP Fatal error: Uncaught TypeError: stream_isatty(): Argument #1 ($stream) must be of type resource, int given in ... code on line ...
The example code:
$ php --run '$r = (int)STDOUT;
var_dump(posix_isatty($r));
var_dump(stream_isatty($r));'
bool(true)
PHP Fatal error: Uncaught TypeError: stream_isatty(): Argument #1 ($stream) must be of type resource, int given in Command line code:3
Stack trace:
#0 Command line code(3): stream_isatty()
#1 {main}
thrown in Command line code on line 3
TIP: Type errors for stream_isatty()
argument #1 ($stream
) are available in PHP >= 8.0.0.
The above example may also highlight another difference between the two:
The older posix_isatty()
emits warnings on invalid file descriptor parameters, while the newer stream_isatty()
throws stream parameter type errors since PHP 8.0.0.
Also, posix_isatty()
emits a warning if the stream type is not STDIO.
Example: posix_isatty() emitting a warning (PHP CLI SAPI)PHP Warning: posix_isatty(): Could not use stream of type '...' in ... on line ...
$ php --run '$r = fopen("php://temp", "rb");
var_dump(posix_isatty($r));
var_dump(stream_isatty($r));'
PHP Warning: posix_isatty(): Could not use stream of type 'TEMP' in Command line code on line 2
bool(false)
bool(false)
NOTE: stream_isatty()
silently returns false
on invalid stream types, those are not value nor type errors.
TIP: Stream handles of integer file descriptors are available in the PHP CLI SAPI via predefined constants: STDIN
(FD 0
), STDOUT
(FD 1
) and STDERR
(FD 2
), cf. I/O streams.
More details and notes in the table and following.
posix_isatty() |
stream_isatty() |
|
---|---|---|
Module ¹ | posix ² ³ |
Core ² ⁴ |
Since | PHP 4 | PHP 7.2 ⁵ |
Stream ⁶ | ❌ ⁷ | ❌ |
Descriptor ⁸ | ❌ | |
Posix | ❌ | ❌ |
Windows ⁵ | ❌ | |
Name ⁹ | $file_descriptor |
$stream |
Type ¹⁰ | resource ⁶ ⁷ | int ⁸ |
resource ⁶ |
Year ¹¹ | 2000 | 2018 |
Source | ext/posix/posix.c | ext/standard/streamsfuncs.c |
Manual | link | link |
php --modules
listing (PHP >= 4.3.3).posix
extension is enabled by default, and may be disabled by using the --disable-posix
option at compile
time.resource
type cannot be type hinted for PHP function parameters.