How to read console/user input in PHP?

南楼画角 提交于 2019-12-30 18:45:38

问题


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?


回答1:


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




回答2:


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";


来源:https://stackoverflow.com/questions/23622141/how-to-read-console-user-input-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!