How to determine if a stream is STDIN in PHP

I am working on some PHP cli tools for php framework, and there is a situation where my script either reads from a file or STDIN . Since not all operations (e.g. fseek() ) are valid on STDIN , I am looking for a way to detect this.

0
source share
2 answers

It turns out that the stream_get_meta_data() function provides a solution when calling standard input, the result is:

 array(9) { ["wrapper_type"]=> string(3) "PHP" ["stream_type"]=> string(5) "STDIO" ["mode"]=> string(1) "r" ["unread_bytes"]=> int(0) ["seekable"]=> bool(false) ["uri"]=> string(11) "php://stdin" ["timed_out"]=> bool(false) ["blocked"]=> bool(true) ["eof"]=> bool(false) } 

So you can do a simple string comparison on uri:

 function isSTDIN($stream) { $meta = stream_get_meta_data($stream); return strcmp($meta['uri'], 'php://stdin') == 0; } 

This solution will work if using a constant STDIO stream, or the old fopen('php://stdin', 'r') , which is still hidden in the old code.

+4
source

Just check if($fp === STDIN)

+1
source

Source: https://habr.com/ru/post/1433481/


All Articles