Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read console/user input in PHP?

Tags:

terminal

php

I use gets to get an user input in Ruby.

# in 0015.rb
input_num = gets.to_i
p "Your input number is #{input_num}."

And I use it in a terminal.

➜  rubytest: ruby 0015.rb
24
"Your input number is 24."    

Can I do like this in PHP with terminal?

like image 443
shin Avatar asked May 13 '14 03:05

shin


People also ask

How can we take input from user in PHP?

To get input from users, you also have to prompt them to enter something. You can use PHP's `readline() function to get this input from the console.

Which function is used to read data from the console?

In C, the scanf() function is used to read formatted data from the console.

How do I scan a value in PHP?

The sscanf() function parses input from a string according to a specified format. The sscanf() function parses a string into variables based on the format string. If only two parameters are passed to this function, the data will be returned as an array.

How can I take input from HTML to PHP?

Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.


2 Answers

If you don't have readline installed, -or- you're writing a library, you should do this:

if (!function_exists('readline')) {
    function readline($question)
    {
        $fh = fopen('php://stdin', 'r');
        echo $question;
        $userInput = trim(fgets($fh));
        fclose($fh);

        return $userInput;
    }
}

$age = readline('What is your age? ');
echo "You are $age years old.\n";
like image 73
Theodore R. Smith Avatar answered Sep 20 '22 21:09

Theodore R. Smith


I think you are looking for the readline function

$number = readline("Enter a number: ");
echo 'You picked the number: '.$number;

http://www.php.net/manual/en/function.readline.php

like image 38
dmullings Avatar answered Sep 19 '22 21:09

dmullings