Quick Tip #1: Please press a key (CLI)

I saw a question by someone on some site that was asking about running a PHP CLI script until the user pressed a key and then quitting (finishing up, not just an exit).

This should be very simple using STDIN as a file stream.

$cli = fopen('php://stdin', 'r');
function prompt($msg, $cli)
    echo $msg . "\n";
    fgets($cli); // <--- must be last

$key = prompt('Please press a key', $cli);


This essentially runs the ‘prompt’ function once, and executes the code inside of it until it hits the last line. The ‘fgets($cli)’ will cause a pause in script execution as it just starts a read on the STDIN.

Leave a Reply

