How to Handle Standard Input in PHP for General-Purpose Scripting
PHP, typically associated with web development, surprisingly touts its versatility as a general-purpose scripting language. While external input methods are scarce in web applications, when using PHP for broader tasks, it becomes pertinent to manage standard input. Specifically, how can PHP retrieve input from stdin using functions like fgetc()?
Leveraging php://stdin to Access Standard Input
Despite the absence of dedicated console-based input, PHP provides a workaround. You can create a file handle linked to php://stdin, enabling you to subsequently read from it. Utilizing fgets(), you can obtain a complete line of input, or fgetc() to read individual characters.
Consider the following code snippet:
<code class="php"><?php $f = fopen('php://stdin', 'r'); while ($line = fgets($f)) { echo $line; } fclose($f); ?></code>
In this example, we create a file handle ($f) connected to php://stdin, opening it in read mode ('r'). Within the while loop, we use fgets() to read each line from standard input. The loop continues until there is no more input, and finally, we close the file handle using fclose().
This approach allows PHP to interact with standard input effectively, catering to its broader capabilities as a versatile scripting language.
The above is the detailed content of Here are a few question-based titles that fit the article's content: * How Can I Read Standard Input in PHP for General-Purpose Scripting? * Is It Possible to Handle Standard Input in PHP Beyond Web. For more information, please follow other related articles on the PHP Chinese website!