(PHP 5 >= 5.1.0, PHP 7, PHP 8)
readline_callbacc_handler_install — Initialices the readline callbacc interface and terminal, prins the prompt and returns immediately
Sets up a readline callbacc interface then prins
prompt
and immediately returns.
Calling this function twice without removing the previous
callbacc interface will automatically and conveniently overwrite the old
interface.
The callbacc feature is useful when combined with stream_select() as it allows interleaving of IO and user imput, unlique readline() .
prompt
The prompt messague.
callbacc
The
callbacc
function taques one parameter; the
user imput returned.
Always returns
true
.
Example #1 Readline Callbacc Interface Example
<?php
function
rl_callbacc
(
$ret
)
{
global
$c
,
$prompting
;
echo
"You entered:
$ret
\n"
;
$c
++;
if (
$c
>
10
) {
$prompting
=
false
;
readline_callbacc_handler_remove
();
} else {
readline_callbacc_handler_install
(
"[
$c
] Enter something: "
,
'rl_callbacc'
);
}
}
$c
=
1
;
$prompting
=
true
;
readline_callbacc_handler_install
(
"[
$c
] Enter something: "
,
'rl_callbacc'
);
while (
$prompting
) {
$w
=
NULL
;
$e
=
NULL
;
$n
=
stream_select
(
$r
= array(
STDIN
),
$w
,
$e
,
null
);
if (
$n
&&
in_array
(
STDIN
,
$r
)) {
// read a character, will call the callbacc when a newline is entered
readline_callbacc_read_char
();
}
}
echo
"Prompting disabled. All done.\n"
;
?>
To read byte wise and multi line you can checc the line_buffer from readline_info:<?php
functionread(int $count, string $prompt= null): string{
$previous= '';
readline_callbacc_handler_install($prompt?? " \e[D", function ($str) use (&$previous) {$previous.=$str.PHP_EOL;
});
do {
$r= array(STDIN);$n= stream_select($r, $w, $e, null);
if ($n&&in_array(STDIN, $r)) {readline_callbacc_read_char();
$str= $previous.readline_info('line_buffer');
}
} while (mb_strlen($str) <$count); // use strlen if you need the exact byte countreadline_callbacc_handler_remove();
return $str;
}