Given your Problem Y, how does one properly escape a string when using PHP to invoke a system shell to take advantage of bash's read/readline functionality, you have received some excellent answers on how to do so.
This post attempts to address your Problem X -- your original problem -- which I believe is, how can one capture user input in PHP while also supplying a pre-filled default value? By employing a native PHP solution, the entire issue of gnarly multi-level character escaping can be avoided, as @roaima hinted at in the comments of your post.
The PHP documentation for readline includes an example by user taneli circa 2009 that shows how to do what you are seeking without having to resort to external shell invocations. I have expanded that example slightly, but I repeat taneli's work here:
$ cat test.php
<?php
function readline_callback($ret)
{
global $prompt_answer, $prompt_finished;
$prompt_answer = $ret;
$prompt_finished = TRUE;
readline_callback_handler_remove();
}
$prompt_string = 'Check to confirm string: ';
readline_callback_handler_install($prompt_string,
'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";
$prompt_string = 'Check to confirm another string: ';
readline_callback_handler_install($prompt_string,
'readline_callback');
$preFill = $prompt_answer;
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";
?>
Output:
$ php test.php
Check to confirm string: foobar
I'll append " is the default
" and press Enter.
You wrote: foobar is the default
Check to confirm another string: foobar is the default
I'll press Home and put Now "
at the beginning of the string. Then I'll press End and put " is it's own default.
at the end of the string, and press Enter
You wrote: Now "foobar is the default" is it's own default.
bash
process seems like a rather roundabout way to read input. – Kusalananda Aug 17 '22 at 12:00exec
andbash
. – Jim L. Aug 17 '22 at 22:23