php - 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 一起使用。
解决方案
您的最后一个示例使用手册页-c
中的参数:
-c
在目录路径中查找 php.ini 文件或使用指定文件
我猜你要使用-r
:
-r
不使用脚本标签运行 PHP 代码
'<?..?>'
在您的回答中,HELLO
来自外壳,如果您替换-c
为-r
is 不显示任何内容,请继续阅读
以上在我的本地机器上的 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://stdout
并php://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("<<<<<");
在线尝试!
推荐阅读
- c++ - C++ 标准中的 [dcl.fct.def.general]/1 可能存在问题
- google-chrome - 谷歌浏览器是否为每个 HTTP 请求创建一个新的套接字?
- python - 如何检查地理位置是否在半径范围内?
- eclipse - 启动 Eclipse RAP 时发生内部错误
- python - 尝试迭代和比较列表和字典中的值时出现类型错误
- amazon-web-services - 如何从 AWS 中的前缀恢复多个文件
- mule - 使用 dataweave 创建 xml 片段(即删除根元素)
- api - API中的函数自己进行系统调用还是API进行的系统调用由运行时支持系统中的系统调用接口辅助?
- javascript - 提供给 super() 的函数中的引用类实例
- c++ - 在 File 对象中创建指向第一个字符的指针