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 — Gets character from file pointer
Descrierea
Gets a character from the given file pointer.
Parametri
- handle
-
Indicatorul fişierului trebuie să fie valid şi trebuie să indice la un fişier deschis cu succes cu ajutorul fopen() sau fsockopen() (şi să nu fie închis cu fclose()).
Valorile întroarse
Returns a string containing a single character read from the file pointed to by handle . Returns FALSE on EOF.
Această funcţie poate întoarce valoarea Boolean FALSE, dar poate de asemenea întoarce o valoare non-Boolean care evaluează în FALSE, cum ar fi 0 sau "". Vă rugăm să citiţi secţiunea despre tipul Boolean pentru mai multe informaţii. Utilizaţi operatorul === pentru a verifica valoarea întoarsă de această funcţie.
Exemple
Example #1 A fgetc() example
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>
Note
Notă: Această funcţie acceptă şi date binare.
Vedeţi de asemenea
- fread() - Binary-safe file read
- fopen() - Opens file or URL
- popen() - Opens process file pointer
- fsockopen() - Open Internet or Unix domain socket connection
- fgets() - Gets line from file pointer
fgetc
11-May-2009 05:30
24-Mar-2009 03: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"` ) );
