问题描述
我正在为php框架开发一些PHP cli工具,但有时我的脚本会从文件或 STDIN
中读取.由于并非所有操作(例如 fseek()
)都在 STDIN
上有效,因此我正在寻找一种检测此情况的方法.
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.
推荐答案
结果证明,函数 stream_get_meta_data()
提供了一种解决方案,当在标准中调用时,结果是:
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)
}
因此您可以在uri上做一个简单的字符串比较:
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;
}
无论使用恒定流 STDIO
还是旧的 fopen('php://stdin','r')
(仍然潜伏),此解决方案都将有效在旧代码中.
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.
这篇关于如何确定流在PHP中是否为STDIN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!