Concept
How can PHP read and clean user input from standard input?
ComputerScienceOne / Converting Units
"The function fgets (short for file get string) using the keyword STDIN (Standard Input) returns, as a string, everything the user enters up to and including the enter key, interpreted as the endline character. To remove the endline character, you can use trim, which removes leading and trailing whitespace from a string. A full example is: printf(\"Please enter a number: \"); $a = fgets(STDIN); $a = trim($a); Alternatively, lines 3–4 could be combined into one: $a = trim(fgets(STDIN)); The call to fgets waits, referred to as “blocking,” for the user to enter input. The user is free to start typing, and when they are done, they hit the enter key, at which point the program resumes, reads the input from the standard input buffer, and returns it as a string value assigned to the variable $a. Standard input is unstructured, so the user is free to type whatever they want. If we prompt the user for a number but they enter non-numerical input, we may get incorrect results. We can use conversion functions to attempt to properly convert the values, although this only guarantees that the resulting variable is of the type we want, such as an integer or floating-point value. Standard input is not a good mechanism for reading input, but it provides a good starting point for developing a few simple programs."
Related Ideas
- How does PHP perform basic input and output?ComputerScienceOne · Basic I/O
- How can a PHP program prompt for the coefficients of a quadratic polynomial?ComputerScienceOne · Computing Quadratic Roots
- How can PHP conditionals validate income and calculate life and taxes?ComputerScienceOne · Life & Taxes
- How can PHP values and variable states be converted and checked explicitly?ComputerScienceOne · Type Juggling
- How do you catch exceptions in PHP?ComputerScienceOne · Catching Exceptions
- How do you read numeric input from a user in Java with Scanner?ComputerScienceOne · Converting Units
- How does scanf() read integer, character, and floating-point input in C?ComputerScienceOne · Basic I/O
- How does PHP convert numeric strings during arithmetic operations?ComputerScienceOne · Type Juggling