The best and simplest way to get input from a user in the CLI with only PHP is to use fgetc() function with the STDIN constant:
<?php
echo 'Are you sure you want to quit? (y/n) ';
$input = fgetc(STDIN);
if ($input == 'y')
{
exit(0);
}
?>
fgetc
(PHP 4, PHP 5)
fgetc — Haalt één teken op uit de bestands pointer
Beschrijving
string fgetc
( resource $handle
)
Geeft een string terug met één teken, die gelezen is uit de bestands pointer handle . Geeft FALSE bij EOF.
De bestands pointer moet geldig zijn, en moet verwijzen naar een bestand dat succesvol geopend is door fopen(), popen(), of fsockopen().
Warning
Deze functie kan FALSE teruggeven, maar ook een andere waarde die naar FALSE evalueert, zoals 0 of "". Gebruik de === operator om de teruggeven waarde van deze functie te testen.
Example#1 Een fgetc() voorbeeld
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Kan bestand somefile.txt niet openen';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>
Note: Deze functie is binary-safe
Zie ook fread(), fopen(), popen(), fsockopen(), en fgets().
fgetc
alex at alexdemers dot me
11-May-2009 07:30
11-May-2009 07:30
ktraas at gmail dot com (Kevin Traas)
24-Mar-2009 04:08
24-Mar-2009 04:08
I was using command-line PHP to create an interactive script and wanted the user to enter just one character of input - in response a Yes/No question. Had some trouble finding a way to do so using fgets(), fgetc(), various suggestions using readline(), popen(), etc. Came up with the following that works quite nicely:
$ans = strtolower( trim( `bash -c "read -n 1 -t 10 ANS ; echo \\\$ANS"` ) );
