In short, PHP was not created for this, but you can get some help from one of these extensions . I'm not sure how thorough they are, but you probably want to use a text library user interface. (And really, you probably don't want to use PHP for this.)
All that being said, you need to get non-blocking input from the STDIN character by character. Unfortunately, most terminals are buffered from a PHP perspective, so you won't get anything until a key is pressed.
If you run stty -icanon (or the equivalent of your OS) on your terminal to disable buffering, then basically the following short program works:
<?php stream_set_blocking(STDIN, false); $line = ''; $time = microtime(true); $prompt = '> '; echo $prompt; while (true) { if (microtime(true) - $time > 5) { echo "\nTick...\n$prompt$line"; $time = microtime(true); } $c = fgetc(STDIN); if ($c !== false) { if ($c != "\n") $line .= $c; else { if ($line == 'exit' || $line == 'quit') break; else if ($line == 'help') echo "Type exit\n"; else echo "Unrecognized command.\n"; echo $prompt; $line = ''; } } }
(It uses a local echo, which allows you to print characters as you type them).
As you can see, we just go in cycles forever. If the character exists, add it to $line . If you press enter, execute $line . Meanwhile, we mark every five seconds to show that we can do something else while we wait for input. (This will consume the maximum processor, you will have to release sleep() to get around this.)
This does not mean that this is a practical example in itself, but perhaps you will think in the right direction.
source share