PHP standard input?

Viewed 85196

I know PHP is usually used for web development, where there is no standard input, but PHP claims to be usable as a general-purpose scripting language, if you do follow it's funky web-based conventions. I know that PHP prints to stdout (or whatever you want to call it) with print and echo, which is simple enough, but I'm wondering how a PHP script might get input from stdin (specifically with fgetc(), but any input function is good), or is this even possible?

10 Answers

It is possible to read the stdin by creating a file handle to php://stdin and then read from it with fgets() for a line for example (or, as you already stated, fgetc() for a single character):

<?php
$f = fopen( 'php://stdin', 'r' );

while( $line = fgets( $f ) ) {
  echo $line;
}

fclose( $f );
?>

Reading from STDIN is recommended way

<?php
while (FALSE !== ($line = fgets(STDIN))) {
   echo $line;
}
?>

A simple method is

$var = trim(fgets(STDIN));

You can use fopen() on php://stdin:

$f = fopen('php://stdin', 'r');

IIRC, you may also use the following:

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

Technically the same, but a little cleaner syntax-wise.

Instead of manually opening STDIN stream, use built in readline() function if you just want to read a single line without too much a hassle :

<?php
$age= readline("Enter your age: ");
echo "Your age is : ".$age;

PHP documentation is your friend : https://www.php.net/manual/en/function.readline.php

Related