Using Martins Example above, and adding user3684669 code with a little modification of my own. Here is a small program displaying a clock and updating every second. When ever a key is pressed I echo it to the screen. I also hide the default echoing of the character to the screen. Works in Linux.
<?php
//-- Save the keyboard state
//-- then use cbreak and turn off echo
$stty_orig = '';
function init_keyboard() {
global $stty_orig;
$stty_orig = shell_exec("stty -g");
system('stty cbreak -echo');
}
//-- Return keyboard state
function close_keyboard() {
global $stty_orig;
system('stty '.$stty_orig);
}
//-- clear the screen
function clear() {
echo "\x1B[2J\x1B[0m";
}
//-- move cursor to x,y on the screen
function gotoxy($x, $y) {
echo "\x1B[".$y.";".$x."H";
}
//-- print a string at x,y on the screen
function printxy($x, $y, $str) {
gotoxy($x,$y);
echo $str;
}
//-- Check if we have a character and return it if we do.
function non_block_read($fd) {
$read = array($fd);
$write = array();
$except = array();
$result = stream_select($read, $write, $except, 0);
if($result === false) throw new Exception('stream_select failed');
if($result === 0) return false;
$data = stream_get_line($fd, 1);
return $data;
}
//-- main program starts here.
init_keyboard();
clear();
printxy(20,15,'Press Q to quit!');
while(1) {
$x = "";
if($x = non_block_read(STDIN)) {
//echo "Input: " . $x . "\n";
// handle your input here
printxy(20,13,'Last Key Pressed: ['.$x."] ");
if ($x == 'Q') {
printxy(1,20,"bye!\n");
break;
}
} else {
// perform your processing here
$date_time = date('F j,Y h:i:sa');
printxy(20,12,$date_time." ");
}
sleep(1);
}
close_keyboard();
fread()return a FALSE? How would it differentiate that from EOF? It seems to me you need some sort of test other thanfread()to determine whether there's waiting data on stdin, since there isn't a descriptive failure.freadwill not return, i.e. pause the execution of the script, until input is given toSTDIN. Basicly what I want, is to check if there is any user input toSTDIN, and if not, continue, or else run some other stuff.fread()should immediately return, even if it couldn't read the amount of data, that it should read (the second argument), but less then this. In this case it should return an empty string. @Petah did you tryfopen('php://stdin)? I vaguely remember, that I had issues withSTDINearlier.stream_set_blocking(STDIN, false)is thatfread()never waits, andif (strlen(fread($stdin,1)) == 0), then nothing is waiting to be input?