How to use STDOUT in php – Php

Photo of author
Written By M Ibrahim
command-line composer-php

Quick Fix: PHP’s STDOUT and STDIN are used for input and output operations. STDIN reads input from a source, often the command line, while STDOUT writes output to a destination, often the console or a file. To use STDOUT in PHP, you can use the fwrite() function, which takes the STDOUT stream as the first argument and the output string as the second argument.

The Solutions:

Solution 1: Using STDIN and STDOUT

In PHP, you can use the following idioms to handle input and output streams:

  • $input = fgets(STDIN);: Reads a line from the standard input stream (STDIN)
  • fwrite(STDOUT, $output);: Writes data to the standard output stream (STDOUT)

When using these idioms from the command line, you can pipe input and output as follows:

  • cat "input.txt" | php script.php > "output.txt": Pipes the contents of “input.txt” into the PHP script and redirects the output to “output.txt”
  • php script.php < input.txt > output.txt: Pipes the contents of “input.txt” into the PHP script and redirects the output to “output.txt”
  • echo "input..." | php script.php | sort | tee output.txt: Pipes the input into the PHP script, sorts it, and then writes the result to “output.txt”

Remember to keep the input and output streams separate (never cross the streams) to ensure proper functionality.

Solution 2: Use STDIN and STDOUT Constants Directly

To use STDOUT in PHP, you can directly use the STDOUT constant, which represents a resource connected to the standard output stream. Here’s an example:


Note that STDOUT is already a resource, so there is no need to open it explicitly. You can directly write to it using fwrite().

Solution 1: Using STDOUT

To use STDOUT in PHP, you can use the built-in function `fopen()`. This function opens a file or URL for reading or writing. In this case, you want to open STDOUT for writing, so you would use the following code:

$out = fopen('php://stdout', 'w');

Once you have opened STDOUT, you can use the `fwrite()` function to write data to it. For example:

fwrite($out, 'Hello, world!');

When you are finished writing to STDOUT, you should close the file using the `fclose()` function:

fclose($out);