Home  >  Article  >  Backend Development  >  How Can I Read Standard Input (stdin) in PHP?

How Can I Read Standard Input (stdin) in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 16:09:49665browse

How Can I Read Standard Input (stdin) in PHP?

Reading Standard Input in PHP

While PHP is commonly used for web development, it's also a general-purpose scripting language. One aspect that may be less familiar is the possibility of reading input from standard input (stdin). This article explores how to achieve this in PHP, particularly using the fgetc() function.

In PHP, standard output is generally available through functions such as print and echo. However, to read from stdin, we must create a file handle and then use the fgets() function for line input or fgetc() for character input.

The following script demonstrates how to read from stdin using PHP:

<code class="php"><?php
$f = fopen('php://stdin', 'r');

while ($line = fgets($f)) {
  echo $line;
}

fclose($f);
?></code>

This script opens a file handle to stdin using fopen('php://stdin', 'r'). The fgets() function is then employed to read lines from stdin, and each line is echoed to the standard output.

By following these steps, you can easily read standard input in PHP, expanding its functionality beyond web development into general-purpose scripting scenarios.

The above is the detailed content of How Can I Read Standard Input (stdin) in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn