Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
读取STDIN时出现PHP语法错误_Php_Syntax Error_Stdin - Fatal编程技术网

读取STDIN时出现PHP语法错误

读取STDIN时出现PHP语法错误,php,syntax-error,stdin,Php,Syntax Error,Stdin,我正在用PHP构建一个CLI脚本,需要从STDIN读取内容并将其处理为变量。它是可执行的,但结果与调用“php”命令的参数相同 它是由WHM事件挂钩触发运行的脚本 文件如下: #!/usr/bin/php -q <?php $switches = (count($argv) > 1) ? $argv : array(); if (in_array('--describe', $switches)) { echo json_encode(describe());

我正在用PHP构建一个CLI脚本,需要从STDIN读取内容并将其处理为变量。它是可执行的,但结果与调用“php”命令的参数相同

它是由WHM事件挂钩触发运行的脚本

文件如下:

#!/usr/bin/php -q

<?php

$switches = (count($argv) > 1) ? $argv : array();

if (in_array('--describe', $switches)) {
    echo json_encode(describe());
    exit;
} elseif (in_array('--debug', $switches)) {
    list($status, $msg) = debug();
    echo "$status $msg";
    exit;
} else {
    echo '0 myapp/whm.php needs a valid switch';
    exit(1);
}


function getStdInStream()
{
    $input   = fopen('php://stdin', 'r');
    $rawData = '';

    if (is_resource($input)) {
        stream_set_blocking($input, 0);

        while (($line = fgets($input, 1024)) !== false) {
            $rawData .= trim($line);
        }

        fclose($input);
    }

    if ($rawData) {
        $data = json_decode($rawData, true);
    } else {
        $data = array('context'=>array(), 'data'=>array(), 'hook'=>array());
    }

    return $data;
}

function describe()
{
    $debug = array(
        'category' => 'Cpanel',
        'event'    => 'UAPI::Branding::get_application_information',
        'stage'    => 'pre',
        'hook'     => '/usr/local/cpanel/3rdparty/bin/hooktest --debug',
        'exectype' => 'script',
    );
    return array($debug);
}

function debug()
{
    $status = 1;
    $msg = 'Triggered!';

    $input = getStdInStream();

    return array($status, $msg);
}

刚刚找到了一个解决方案。 从
#更改hashbang/usr/bin/php-q
#/usr/bin/env-php
使php以不同的方式解释脚本

我注意到,使用原始脚本(从问题中),全局常量
STDIN
STDOUT
没有定义。使用
#/usr/bin/env php也解决了这个问题

根据
env
的手册页,它在修改过的环境中运行程序,而不是“仅仅”将脚本传递给解释器(本例中为php)。是什么让我认为它正确地将
stdin
stdout
重定向到环境中的脚本代码

$ /usr/local/cpanel/3rdparty/bin/hooktest
<br />
<b>Parse error</b>:  syntax error, unexpected '{' in  <b>/usr/local/cpanel/3rdparty/bin/hooktest</b> on line <b>24</b><br />
PHP 5.4.41 (cgi-fcgi) (built: May 22 2015 16:12:44)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2014 Zend Technologies