代码之家  ›  专栏  ›  技术社区  ›  Chris Lutz

PHP标准输入?

  •  47
  • Chris Lutz  · 技术社区  · 16 年前

    我知道PHP通常用于Web开发,在那里 没有标准的输入,但是PHP声称可以作为通用的脚本语言使用,如果您遵循它的基于Web的时髦约定的话。我知道PHP打印到 stdout (或任何你想称之为它的东西) print echo ,这很简单,但我想知道PHP脚本如何从 stdin (特别是 fgetc() ,但是任何输入函数都是好的),或者这是可能的吗?

    9 回复  |  直到 7 年前
        1
  •  67
  •   Dave Jarvis James Eichele    12 年前

    可以阅读 stdin 通过创建文件句柄 php://stdin 然后用 fgets() 例如,对于一行(或者,正如您已经说过的, fgetc() 对于单个字符):

    <?php
    $f = fopen( 'php://stdin', 'r' );
    
    while( $line = fgets( $f ) ) {
      echo $line;
    }
    
    fclose( $f );
    ?>
    
        2
  •  36
  •   anatoly techtonik Tony    14 年前

    从阅读 斯坦丁 recommended way

    <?php
    while (FALSE !== ($line = fgets(STDIN))) {
       echo $line;
    }
    ?>
    
        3
  •  14
  •   mjs    13 年前

    为了避免把文件句柄搞得乱七八糟,请使用 file_get_contents() php://stdin :

    $ echo 'Hello, World!' | php -r 'echo file_get_contents("php://stdin");'
    Hello, World!
    

    (如果您正在从 stdin 您可能希望使用filehandle方法,但这对于许多兆字节来说是很好的。)

        4
  •  11
  •   Luke Sampson    11 年前

    一个简单的方法是

    $var = trim(fgets(STDIN));
    
        5
  •  8
  •   Greg    16 年前

    你可以使用 fopen() php://stdin :

    $f = fopen('php://stdin', 'r');
    
        6
  •  6
  •   redolent    11 年前

    一炮打完:

    $contents = file_get_contents("php://stdin");
    echo $contents;
    
        7
  •  5
  •   Fritz H    16 年前

    IIRC,您也可以使用以下内容:

    $in = fopen(STDIN, "r");
    $out = fopen(STDOUT, "w");
    

    从技术上讲是一样的,但从语法上讲比较干净。

        8
  •  2
  •   Andy Ali    9 年前

    这也适用于:

    $data = stream_get_contents(STDIN);
    
        9
  •  0
  •   NVRM    7 年前

    使用fgets时,如果 stdin 未设置或为空,包括在使用 @ php error control operator .

    #!/usr/bin/php
    <?php
    $pipe = @trim(fgets(STDIN));
    // Script was called with an empty stdin
    // Fail to continue, php warning 
    

    可以通过设置 stream_set_blocking 在php头上:

    #!/usr/bin/php
    <?php
    stream_set_blocking(STDIN, 0);
    $pipe = @trim(fgets(STDIN));
    // Script was called with an empty stdin
    // No errors or warnings, continue