11 / 11
Mar 2013

<?php
$stdin = fopen('php://stdin', 'r');
while (true) {
        $input = fgets($stdin, 3);
        if ($input == 42) {
                break;
        } else {
                echo $input;
        }
}
fclose($stdin);
?>
  • created

    Aug '05
  • last reply

    Mar '13
  • 10

    replies

  • 2.9k

    views

  • 8

    users

  • 2

    links

5 months later

Thanks a lot.

I often use PHP to code website but i don't know how to read datas from standard input.

But now I can do it.
Thanks !

8 months later

Tip: instead of $stdin = ..., just remove the first line of code ("$stdin = ...") and replace all $stdin with the constant STDIN. Also remove the fclose line.

<?php
while (true) {
        $input = fgets(STDIN, 3);
        if ($input == 42) {
                break;
        } else {
                echo $input;
        }
}
?>

[/code]

3 years later

I have made another program, returning the same result but it didn't accept it. I don't know why. Please tell me why does this happen?
This is the code:

<?
while (true) {
$strName = fread(STDIN,3);
if ($strName == 42) {
echo "\n";
        exit;
}
echo "$strName";
}
?>

yes, I figured out that it's not the best way to do it. But I couldn't find any input which makes my version fail. It still outputs the same thing.

If you haven't already found the problem, I suspect it stems from the fact that fgets stops at a newline and that fread doesn't.

Once I get access to ideone tonight I can put together a test case (I don't know enough about php to make one on the fly)

If you attempt it yourself, you'll need to use numbers less than 10 to make it overflow into the next line.

1
12
42
The first read will contain "1\n1" and that won't equal 42. Then it Will read "2\n4" and that won't equal 42. Then it will read "2" and hit EOF and return false.

Something along those lines I suspect.

1 year later

Thanks for the code.
It worked, but I don't understand why I need to use numbers under 10.

Why wouldn't you?

1 year later

<?php
$show = true;
while($show){
	$in = trim(fgets(STDIN));
	if($in=="42") $show=false;
	if($show)
		print $in."\n";
}
?>