0

I was working on my project and suddenly stdin in PHP stops working.

I have code in PHP:

test.php

<?php

$stdin = file_get_contents('php://input');

echo ">>>>>";
echo $stdin;
echo "<<<<<";

and I'm executing it with:

echo 'HELLO' | php -f test.php
>>>>><<<<<

This works fine:

echo 'HELLO' | php -c "echo file_get_contents('php://input');"
HELLO

and it doesn't work, I'm spending way too much time on this. Why this simple code doesn't work? Any clues? I'm using Fedora GNU/Linux with php 7.4.19.

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • Have a look at `echo 'HELLO' | php -c "blah"`. Your command line switch is not doing what you think it is. – cmbuckley Jun 24 '21 at 21:40
  • `-c` isn't "run this code", `-r` is. Your second example is equivalent to `echo 'HELLO' | php` where PHP will interpret stdin as a script to be executed. Since there are no tags or code, it's passed as-is to stdout. `echo 'HELLO' | php -r "echo '>>'; echo file_get_contents('php://input'); echo '<<';"` is equivalently broken as the first snippet, and 0stone0's answer is correct. – Sammitch Jun 24 '21 at 21:40

1 Answers1

3

Your last example uses the -c parameter, from the man page:

-c

Look for php.ini file in the directory path or use the specified file

I guess you ment to use -r:

-r

Run PHP code without using script tags '<?..?>'

In your answer, the HELLO comes from the shell, if you replace -c with -r is shows nothing, for that, please continue reading

The above seen in shell, on my local machine, in a snippet because the answer is getting way to long

$
$ echo 'HELLO' | php -c "echo 'Test'; echo file_get_contents('php://input');"
HELLO
$
$ # HELLO Comes from shell, no 'echo 'Test';
$
$ echo 'HELLO' | php -r "echo 'Test'; echo file_get_contents('php://input');"
Test%
$
$ # With `-r` only the Test echo, because php:// input is empty
$
$
$ echo 'HELLO' | php -r "echo 'Test'; echo file_get_contents('php://stdin');"
TestHELLO
$
$ # If we use php://stdin we get both the echo's
$

From the documentation:

php://input is a read-only stream that allows you to read raw data from the request body

Your data is in stdin, so you'll need file_get_contents('php://stdin'):

php://stdin, php://stdout and php://stderr allow direct access to the corresponding input or output stream of the PHP process.

Source of above quotes


<?php

$stdin = file_get_contents('php://stdin');

echo ">>>>>";
echo $stdin;
echo "<<<<<";

Try it online!


Another option is to use stream_get_contents(STDIN):

<?php

$stdin = stream_get_contents(STDIN);

print(">>>>>");
print($stdin);
print("<<<<<");

Try it online!

0stone0
  • 34,288
  • 4
  • 39
  • 64