Open In App

How to read user or console input in PHP ?

In PHP, the console is a command-line interface, which is also called interactive shell. We can access it by typing the following command in a terminal: 

php -a

If we type any PHP code in the shell and hit enter, it is executed directly and displays the output or shows the error messages in case of any error. A sample run of a PHP code, that reads input from PHP console looks like this: 
 



In this article, We will discuss two methods for reading console or user input in PHP: 
Method 1: Using readline() function is a built-in function in PHP. This function is used to read console input. 
The following things can be achieved by readline() function
 






<?php
  
// For input
// Hello World
$a = readline('Enter a string: ');
  
// For output
echo $a;    
?>

Output: 

Enter a string: GeeksforGeeks
GeeksforGeeks




<?php
   
// Input section
// $a = 10
$a = (int)readline('Enter an integer: ');
  
// $b = 9.78
$b = (float)readline('Enter a floating'
            . ' point number: ');
  
// Entered integer is 10 and
// entered float is 9.78
echo "Entered integer is " . $a 
    . " and entered float is " . $b;
?>

Output: 

Enter an integer: 10
Enter a floating point number: 9.78
Entered integer is 10 and entered float is 9.78
$a = readline();




<?php
   
// Input 10 20
list($var1, $var2
        = explode(' ', readline());
   
// Typecasting to integers
$var1 = (int)$var1;
$var2 = (int)$var2;
   
// Printing the sum of var1 and var2.
// The sum of 10 and 20 is 30
echo "The sum of " . $var1 . " and "
    . $var2 . " is " . ($var1 + $var2);
?>

Output:
The sum of 10 and 20 is 30
 




<?php
   
// For input
// 1 2 3 4 5 6
$arr = explode(' ', readline());
  
// For output
print_r($arr);
  
/*Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)*/
   
?>

Output: 

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)

Method 2: Using fscanf() function works same as the fscanf() function in C. We can read 2 integers from Keyboard(STDIN) as below: 




<?php
  
// Input 1 5
fscanf(STDIN, "%d %d", $a, $b);
   
// Output
// The sum of 1 and 5 is 6
echo "The sum of " . $a . " and "
    . $b . " is " . ($a + $b);
?>

Output: 

The sum of 1 and 5 is 6

Comparison between two methods: 

PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples.


Article Tags :