88

I want to be able to let a PHP program wait for user's input. For example:

  1. Script requests authorization code from server (this code will be sent via e-mail)
  2. Script waits for user to enter authorization code
  3. Script continues

How should I do step 2? (Is it possible?)

5
  • 2
    How about read the man page on php cli usage, particularly useful would be this comment -> php.net/manual/en/features.commandline.php#94924 Commented Mar 10, 2013 at 12:50
  • Thanks @Crisp, you can make that an answer. Commented Mar 10, 2013 at 12:51
  • 1
    I don't think this is a duplicate of the answer linked. You could use the code provided by Crisp which involves file handles. Or simply use the readline() function which will prompt for user input: php.net/manual/en/function.readline.php assuming your PHP was compiled with readline support. Commented Apr 2, 2014 at 9:49
  • @Gabe the question is maybe not the same, but an answer to this question was given on the other question, which makes closing fair. Commented Apr 2, 2014 at 9:51
  • You might use the built-in php function: "readline()", usage: $line = readline("Command: "); Commented Dec 16, 2014 at 18:49

1 Answer 1

212

The php man page for the cli has a comment here detailing a solution, (copied here for anyone else looking)

<?php
echo "Are you sure you want to do this?  Type 'yes' to continue: ";
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
if(trim($line) != 'yes'){
    echo "ABORTING!\n";
    exit;
}
fclose($handle);
echo "\n"; 
echo "Thank you, continuing...\n";
?>
Sign up to request clarification or add additional context in comments.

8 Comments

Can this be doing loop, that terminates on input?
might as well just do $line = trim(fgets($handle)) since 99.9% of the time you wouldn't want the newline in the captured input
You can use additional check if( php_sapi_name() === 'cli' ) { } to determine if the current invocation is from CLI stackoverflow.com/questions/933367/…
@Hugo: You should use readline() for this. This is unnecessarily complicated.
|