首页 > 解决方案 > file_get_contents('php://input') 不适用于 Bash 管道

问题描述

我正在处理我的项目,突然 PHP 中的标准输入停止工作。

我在 PHP 中有代码:

测试.php

<?php

$stdin = file_get_contents('php://input');

echo ">>>>>";
echo $stdin;
echo "<<<<<";

我正在执行它:

echo 'HELLO' | php -f test.php
>>>>><<<<<

这工作正常:

echo 'HELLO' | php -c "echo file_get_contents('php://input');"
HELLO

它不起作用,我在这上面花了太多时间。为什么这个简单的代码不起作用?有什么线索吗?我将 Fedora GNU/Linux 与 php 7.4.19 一起使用。

标签: phpbash

解决方案


您的最后一个示例使用手册页-c中的参数:

-c

在目录路径中查找 php.ini 文件或使用指定文件

我猜你要使用-r

-r

不使用脚本标签运行 PHP 代码'<?..?>'

在您的回答中,HELLO来自外壳,如果您替换-c-ris 不显示任何内容,请继续阅读

以上在我的本地机器上的 shell 中看到的片段中,因为答案越来越长

$
$ echo 'HELLO' | php -c "echo 'Test'; echo file_get_contents('php://input');"
HELLO
$
$ # HELLO Comes from shell, no 'echo 'Test';
$
$ echo 'HELLO' | php -r "echo 'Test'; echo file_get_contents('php://input');"
Test%
$
$ # With `-r` only the Test echo, because php:// input is empty
$
$
$ echo 'HELLO' | php -r "echo 'Test'; echo file_get_contents('php://stdin');"
TestHELLO
$
$ # If we use php://stdin we get both the echo's
$


文档中:

php://input是一个只读流,允许您从请求正文中读取原始数据

您的数据在 中stdin,因此您需要file_get_contents('php://stdin')

php://stdin,php://stdoutphp://stderr允许直接访问 PHP 进程的相应输入或输出流。

以上报价来源


<?php

$stdin = file_get_contents('php://stdin');

echo ">>>>>";
echo $stdin;
echo "<<<<<";

在线尝试!


另一种选择是使用stream_get_contents(STDIN)

<?php

$stdin = stream_get_contents(STDIN);

print(">>>>>");
print($stdin);
print("<<<<<");

在线尝试!


推荐阅读