How to read from stdin

Add a reply

Posted by Nibbler 718 days ago:
Reading from stdin is not something familiar to many php coders, so here are a few ways to read in the puzzle you are given from stdin using the PHP CLI.

$s=fgets(STDIN);

Reads in a complete line of input as a string, complete with end of line character.

$c=fgetc(STDIN);

Reads in a single character.

Also worth looking at are fscanf(), fgetcsv(), fread()

To test your scripts you can use this command from a linux shell (other operating systems may differ)

php your_script.php < test.txt

Where test.txt is a plain text file containing your sample input.
Posted by carldr 718 days ago:
Thanks for that Nibbler, I'm sure it will be useful to a lot of PHP coders out there.
Posted by toxik 311 days ago:
foreach(explode("\n",fread(STDIN))as$l)echo "line: $l";

That's how one could read line-by-line without the woes of the trailing line delimiter.
Posted by eros 306 days ago:
Can you tell me how can i do to try in my computer (windows) the STDIN. My apache is xampp.

PD: My english is not good. Sorry
Posted by eros 305 days ago:
i cant read with fgets(STDIN) but i do that:
$s=fopen('php://stdin','r')
while($a=fgets($s)){
.
.
.
}

fgets(STDIN) Just read one line and then does not return any result . fgets(STDIN) don't do anything just return error.

Add a reply