我想要的是能够可选地将STDIO输送到PHP脚本。如果不是,它将从文件中获取输入。所以有时我会简单地运行脚本,其他时候我会做一些类似的事情
grep text logfile | php parseLog.php我有一个非常类似的循环,当STDIO存在时,它可以很好地工作:
while (FALSE !== ($line = fgets(STDIN)))
{
$customLogArr[]=$line;
}当没有STDIO,虽然它停止等待一些,它甚至没有进入循环。
我想要做的是能够检测我是否有STDIO输入。有办法吗?
发布于 2015-02-17 21:35:36
if(FALSE !== ftell(STDIN))
{
while (FALSE !== ($line = fgets(STDIN)))
{
$customLogArr[]=$line;
}
}对于STDIN,如果无法读取,ftell()将返回false。
发布于 2017-10-16 13:15:07
看起来有些事情变了,或者这些答案都没有正确的答案。您不能简单地通过ftell(STDIN)查看是否有从STDIN传递的数据。
<?php
$stdin = fopen('php://stdin', 'r');
var_dump(ftell($stdin));输出
-:4:
bool(false)这是来自php -v的输出
PHP 7.0.22-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
with Zend OPcache v7.0.22-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies
with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans当我尝试使用STDIN常量时,我得到
PHP Notice: Use of undefined constant STDIN - assumed 'STDIN' in - on line 3发布于 2021-01-08 11:05:39
使用posix_isatty()函数可能要简单一些。
<?php
/**
* parseLog.php
*/
echo (posix_isatty(STDIN)) ? 'no stdin' . PHP_EOL : file_get_contents('php://stdin');$ echo 'foo' > ./logfile.txt
$ cat logfile.txt | php parseLog.php
foo
$ php parseLog.php
no stdinposix_isatty(STDIN)确定STDIN是否打开并连接到终端。因此,在从STDIN接收数据时,它将返回false。
https://stackoverflow.com/questions/28571139
复制相似问题