Php считывание с клавиатуры

readline

Reads a single line from the user. You must add this line to the history yourself using readline_add_history() .

Parameters

You may specify a string with which to prompt the user.

Return Values

Returns a single string from the user. The line returned has the ending newline removed. If there is no more data to read, then false is returned.

Examples

Example #1 readline() Example

//get 3 commands from user
for ( $i = 0 ; $i < 3 ; $i ++) $line = readline ( "Command: " );
readline_add_history ( $line );
>

//dump history
print_r ( readline_list_history ());

//dump variables
print_r ( readline_info ());
?>

User Contributed Notes 17 notes

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

/*
*
I’ve noticed strange behavior from readline while using it for user input from a CLI.

When I press multiple tabs it prints a scandir to the input stream.

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: ‘);

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:

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.

Читайте также:  Rutracker org forum tracker php nm scad

To haukew at gmail dot com:

readline provides more features than reading a single line of input . your example misses line editing and history. If you don’t need that, use something as simple as this:

function readline( $prompt = » )
echo $prompt;
return rtrim( fgets( STDIN ), «\n» );
>

In CGI mode be sure to call:

at the top of your script if you want to be able to output data before and after the prompt.

To stop auto complete , register an auto complete function that returns no matches to auto complete.

function dontAutoComplete ($input, $index)

The readline library is not available on Windows.

if ( PHP_OS == ‘WINNT’ ) echo ‘$ ‘ ;
$line = stream_get_line ( STDIN , 1024 , PHP_EOL );
> else $line = readline ( ‘$ ‘ );
>
?>

If you want to prefill the prompt with something when using readline, this worked for me:

function readline_callback ( $ret )
<
global $prompt_answer , $prompt_finished ;
$prompt_answer = $ret ;
$prompt_finished = TRUE ;
readline_callback_handler_remove ();
>

readline_callback_handler_install ( ‘Enter some text> ‘ ,
‘readline_callback’ );

$prefill = ‘foobar’ ;
for ( $i = 0 ; $i < strlen ( $prefill ); $i ++)
<
readline_info ( ‘pending_input’ , substr ( $prefill , $i , 1 ));
readline_callback_read_char ();
>

$prompt_finished = FALSE ;
$prompt_answer = FALSE ;
while (! $prompt_finished )
readline_callback_read_char ();
echo ‘You wrote: ‘ . $prompt_answer . «\n» ;
?>

I wanted a function that would timeout if readline was waiting too long. this works on php CLI on linux:

function readline_timeout ( $sec , $def )
<
return trim ( shell_exec ( ‘bash -c ‘ .
escapeshellarg ( ‘phprlto=’ .
escapeshellarg ( $def ) . ‘;’ .
‘read -t ‘ . ((int) $sec ) . ‘ phprlto;’ .
‘echo «$phprlto»‘ )));
>

?>

Just call readline_timeout(5, ‘whatever’) to either read something from stdin, or timeout in 5 seconds and default to ‘whatever’. I tried just using shell_exec without relying on bash -c, but that didn’t work for me, so I had to go the round about way.

A workaround if readline is not compiled into php, because for example the command is only needed within an installation routine. It works as follows under Linux:

$f=popen(«read; echo \$REPLY»,»r»);
$input=fgets($f,100);
pclose($f);
echo «Entered: $input\n»;

for some reason readline() doesn’t support unicode, readline STRIPS æøåÆØÅ — for a readline function with unicode support, try
function readline_with_unicode_support (? string $prompt = null ) /*: string|false*/
if ( $prompt !== null && $prompt !== » ) echo $prompt ;
>
$line = fgets ( STDIN );
// readline() removes the trailing newline, fgets does not,
// to emulate the real readline(), we also need to remove it
if ( $line !== false && strlen ( $line ) >= strlen ( PHP_EOL ) && substr_compare ( $line , PHP_EOL , — strlen ( PHP_EOL ), strlen ( PHP_EOL ), true ) === 0 ) $line = substr ( $line , 0 , — strlen ( PHP_EOL ));
>
return $line ;
>

Читайте также:  Основы PHP и MySQL

If you want to block remove previous text and wonder that an empty string does not work: the workaround is to use an space with cursor left:

function readline ()
return rtrim ( fgets ( STDIN ));
>
>

//Example1
$line = new ConsoleQuestion ();
$prompt = «What Is Your Name: » ;
echo $prompt ;
$answer = $line -> readline ();
echo «You Entered: » . $answer ;

//Example2 (comment Ex1 then uncomment Ex2)
/*$prompt = «What Is Your Name: «;
echo $prompt;
$answer = «You Entered: » . rtrim( fgets( STDIN ));
echo $answer;*/

Works under windows, and under php 7.2.0 :

Commande : 658
Commande : 965
Commande : 478
Array
(
[0] => 658
[1] => 965
[2] => 478
)

/**
* readline() with unicode support
* php’s builtin readline has dodgy unicode support, it only works
* with the correct environment locale settings, it doesn’t seem to work at Cygwin (strips æøåÆØÅ),
* and it has historically had bugs like https://bugs.php.net/bug.php?id=81598
* meanwhile this readline has consistent unicode support across all platforms (including Cygwin)
* and doesn’t care about locale settings.
*
* @param string $prompt
* @return string|false
*/
function readline_with_unicode_support (? string $prompt = null ) /*: string|false*/
if ( $prompt !== null && $prompt !== » ) echo $prompt ;
>
$line = fgets ( STDIN );
// readline() removes the trailing newline, fgets() does not,
// to emulate the real readline(), we also need to remove it
if ( $line !== false && strlen ( $line ) >= strlen ( PHP_EOL ) && substr_compare ( $line , PHP_EOL , — strlen ( PHP_EOL )) === 0 ) $line = substr ( $line , 0 , — strlen ( PHP_EOL ));
>
return $line ;
>

  • Readline Functions
    • readline_​add_​history
    • readline_​callback_​handler_​install
    • readline_​callback_​handler_​remove
    • readline_​callback_​read_​char
    • readline_​clear_​history
    • readline_​completion_​function
    • readline_​info
    • readline_​list_​history
    • readline_​on_​new_​line
    • readline_​read_​history
    • readline_​redisplay
    • readline_​write_​history
    • readline

    Источник

    Ввод значений с клавиатуры

    Ввод значений с клавиатуры
    Добрый день, Господа, подскажите в чем проблема, решил попробовать себя в программировании и.

    Ввод значений с клавиатуры
    Необходимо написать программу, в которой значения вводятся с клавиатуры и нужно только чтоб они.

    Ввод значений с клавиатуры
    Добрый вечер, есть вот такой вот просто запрос: SELECT dbo.a.Name,dbo.a.Head,dbo.b.RoomN AS.

    Ввод значений переменных с клавиатуры
    Как в простом си запросить ввод ЧИСЛОВЫХ данных каждого типа char, short и др когда я пишу для.

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
    $_SERVER['PHP_SELF']?>"> a: b:  echo "Решение линейного уравнения a+bx=0 
    "
    ; $a=isset($_GET['a']) ? $_GET['a'] : 6; $b=isset($_GET['b']) ? $_GET['b'] : 2; $x; if($b!=0) { $x=(-$a)/$b; echo "x="; echo $x; } else{ echo "Решения нет"; } ?>

    Уравнение решает не зависимо от того вводились ли данные или нет. Выводит форму для ввода и выводит решение (x=-3) Значения должны вводится произвольные, не именно 6 и 2.

    form name="authForm" method="GET" action=" ">

    Dimedrol, здравствуйте, у меня такой же вопрос, только немного другая ситуация, надеюсь вы мне поможете:
    Дан хеш, содержащий данные вида: (снежный барс, горы; улар, горы; рысь, леса; заяц, леса; краб, море; дельфин, море; рак, водоемы; сом, водоемы.
    Ввести с клавиатуры среду обитания и вывести на экран названия животных, которые там живут.

    такого задание, и вот у меня как у новичка php, возникает вопрос каким путем создать поле ввода данных и соответственно вывод.

    ЦитатаСообщение от zalkom Посмотреть сообщение

    ЦитатаСообщение от zalkom Посмотреть сообщение

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
      $_SERVER['PHP_SELF']?>"> Среда обитания: горы, леса, море или пресные воды 
    if($_GET['a']=="горы") { echo "В горах обитает улар и снежный барс"; } else if($_GET['a'] == "леса") { echo "В лесу обитает рысь и заяц"; } else if($_GET['a'] == "море") { echo "В море обитает краб и дельфин"; } else if($_GET['a'] == "пресные воды") { echo "В пресных водах обитает рак и карась"; } ?>

    Конечно примитивно, но проблема состоит в том, что все как бы работает, когда в форме уже писал среду, но при первом открытии сайта, так скажем, выдает такую ошибку:

    Notice: Undefined index: a in C:\xampp\htdocs\laba\index.php on line 12

    Notice: Undefined index: a in C:\xampp\htdocs\laba\index.php on line 16

    Notice: Undefined index: a in C:\xampp\htdocs\laba\index.php on line 20

    Notice: Undefined index: a in C:\xampp\htdocs\laba\index.php on line 24

    Источник

Оцените статью