PHP 8.6.0 Beta 1 is available for testing

readline

(PHP 4, PHP 5, PHP 7, PHP 8)

readlineЧитает строку

Описание

function readline(? string $prompt = null ): string |false

Функция читает одну строку, которую ввёл пользователь. Строку добавляют в историю команд функцией readline_add_history() .

Список параметров

prompt
Текст приглашения, который функция покажет пользователю в командной строке.

Возвращаемые значения

Функция возвращает одну строку, которую ввёл пользователь. Функция удалит из конца строки, которую вернула командная оболочка, символ новой строки. Функция возвращает false , если не осталось данных для чтения.

Примеры

Пример #1 Пример чтения строки функцией readline()

<?php
// Получим 3 команды от пользователя
for ($i=0; $i < 3; $i++) {
 $line = readline("Command: ");
 readline_add_history($line);
}
// Выведем дамп с историей ввода
print_r(readline_list_history());
// Выведем дамп с переменными
print_r(readline_info());

Нашли ошибку?

ИнструкцияИсправлениеСообщение об ошибке
+Добавить

Примечания пользователей 5 notes

up
12
Antony Penn
6 years ago
Christian's code works well, but if you want to be able to hide the user input and not echo it to screen, you need to add -s to the read command. The code below is an expanded function that allows an optional prompt and optional hiding of the input:
function read_password($prompt=null, $hide=false)
{
 if($prompt) print $prompt;
 $s = ($hide) ? '-s' : '';
 $f=popen("read $s; echo \$REPLY","r");
 $input=fgets($f,100);
 pclose($f);
 if($hide) print "\n";
 return $input;
}
up
7
turdsurfer
9 years ago
If your CLI script accepts input from STDIN and you also want it to prompt for a password (e.g. as mysql client does), then readline() won't work for you. 
What you need to do is read from the terminal device as shown below.
function readline_terminal($prompt = '') {
 $prompt && print $prompt;
 $terminal_device = '/dev/tty';
 $h = fopen($terminal_device, 'r');
 if ($h === false) {
 #throw new RuntimeException("Failed to open terminal device $terminal_device");
 return false; # probably not running in a terminal.
 }
 $line = rtrim(fgets($h),"\r\n");
 fclose($h);
 return $line;
}
$pass = readline_terminal('Password: ');
up
3
cox at idecnet dot com
24 years ago
In CGI mode be sure to call:
ob_implicit_flush(true);
at the top of your script if you want to be able to output data before and after the prompt.
-- Tomas V.V.Cox
up
0
Anonymous
9 years ago
a few observations....
I use Cygwin PHP v7 and readline is available. The readline_list_history() function though is not defined.
A prompt with escape sequences are sanitized, so use something like:
<?php
 echo("\e[0m\e[34mPromt>\e[0m");
 $inp = readline(' ');
?>

I have not fully documented it, but I see that sometimes strings beginning with punctuation characters do not make it into the history with readline_add_history(). They also sometimes clear the prompt string.
up
-3
rojaro at gmail dot com
17 years ago
Note that readline() will return boolean "false" when the user presses CTRL+D.
+Добавить

AltStyle によって変換されたページ (->オリジナル) /