Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 58 / 68

Reading from Standard Input

In this lesson you will learn to read from standard input with fgets(STDIN) so you can build interactive command-line tools. This is for anyone searching for "PHP standard input how to use".

fgets(STDIN) reads one line of input from the keyboard or another source. Use it when a command-line tool needs the user to type something.

The sample code prints a prompt and then reads the input with trim(fgets(STDIN)). Pairing it with trim() to strip the newline and any stray whitespace is the standard way to handle standard input.

A common stumbling block for beginners is that the string from fgets(STDIN) still carries a trailing newline. Without trim() to remove it, later comparisons and output can behave unexpectedly.

Using input without validating it can lead to unexpected errors, so pairing it with a validation step is safer. It is the essential mechanism behind any interactive command-line tool.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)