How to determine if a stream is STDIN in PHP

被刻印的时光 ゝ 提交于 2019-12-24 23:42:05

问题


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


回答1:


Turns out that the function stream_get_meta_data() provides a solution, when called on standard in, 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 compare on the uri:

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

This solution will work whether the constant stream STDIO is used, or the old fopen('php://stdin', 'r'), which still lurks around in old code.




回答2:


Simply check if($fp === STDIN)



来源:https://stackoverflow.com/questions/5572363/how-to-determine-if-a-stream-is-stdin-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!