How can I read the contents of stdin (up until EOF) into a string in PHP?
Use the sys. stdin. readlines() method to read user input until EOF. The readlines() method will return a list containing the lines.
The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.
Standard streams php://stdin, php://stdout and php://stderr allow direct access to standard input stream device, standard output stream and error stream to a PHP process respectively. Predefined constants STDIN, STDOUT and STDERR respectively represent these streams.
ended up figuring it out myself:
$input_data = file_get_contents("php://stdin");
Here's an alternative: You can use stream_get_contents
to get everything from an open stream (AKA a file handle). STDIN
is an already open handle equivalent to what you get if you call fopen('php://stdin')
(see reference: Input/output streams
So: you can use
$input_data = stream_get_contents(STDIN);
which is equivalent to the accepted answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With