我知道PHP通常用于Web开发,因为那里没有标准输入,但PHP声称如果你遵循它的奇特基于Web的惯例,它可作为通用脚本语言使用。我知道PHP使用print
和echo
向stdout
(或你想叫它的任何东西)输出内容,这很简单,但我想知道PHP脚本如何从stdin
(具体来说是使用fgetc()
,但任何输入函数都可以)获取输入,或者这是否可能?
通过创建一个文件句柄到php://stdin
,然后使用fgets()
读取一行(或者如您已经提到的那样,使用fgetc()
读取单个字符),可以读取stdin
。
<?php
$f = fopen( 'php://stdin', 'r' );
while( $line = fgets( $f ) ) {
echo $line;
}
fclose( $f );
?>
从STDIN读取数据是推荐的方式
<?php
while (FALSE !== ($line = fgets(STDIN))) {
echo $line;
}
?>
file_get_contents()
和php://stdin
:
为避免繁琐的文件句柄操作,请使用file_get_contents()
和php://stdin
:
$ echo 'Hello, World!' | php -r 'echo file_get_contents("php://stdin");'
Hello, World!
如果你需要从标准输入流中读取大量数据,你可能需要使用文件句柄的方法,但对于许多兆字节的数据来说,这种方法就足够了。
file_get_contents('php://input')
替代,那个可行。 - ygoe$var = trim(fgets(STDIN));
$contents = file_get_contents("php://input");
。 - Bogdan BurymSTDIN
只适用于控制台使用,而不适用于 POST 请求体。 - ygoe一次性获取所有内容:
$contents = file_get_contents("php://stdin");
echo $contents;
file_get_contents('php://input')
替代,那个可行。 - ygoe$data = stream_get_contents(STDIN);
#!/usr/bin/php
<?php
$pipe = @trim(fgets(STDIN));
// Script was called with an empty stdin
// Fail to continue, php warning
stream_set_blocking
来避免:#!/usr/bin/php
<?php
stream_set_blocking(STDIN, false);
$pipe = @trim(fgets(STDIN));
// Script was called with an empty stdin
// No errors or warnings, continue
echo $pipe . "!";
echo "Hello world" | ./myPHPscript
// Output "Hello world!"
./myPHPscript
// Output "!"
declare(strict_types=1);
指令时,值得注意的是将stream_set_blocking
的第二个参数设置为0
会导致错误,因为该函数期望其第二个参数为有效的布尔值,而不是整数。应改用stream_set_blocking(STDIN, false);
。 - Amin NAIRI$in = fopen(STDIN, "r");
$out = fopen(STDOUT, "w");
从技术上讲,它们是相同的,但语法更加简洁。
如果你只想读取一行而不想费太多力气手动打开STDIN流,请使用内置的readline()函数:
<?php
$age= readline("Enter your age: ");
echo "Your age is : ".$age;
PHP文档是您的好朋友: https://www.php.net/manual/en/function.readline.php
fclose
STDIN
? - Pacerier