Ben S Ben S - 1 year ago 124
PHP Question

PHP - How to read ANSI escape code CSI 6n

How can I read the result of ANSI escape code CSI 6n with PHP ?

(DSR – Device Status Report: https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes)

<?php
fwrite(STDOUT, "\033[6n");
$code = fread(STDIN,1);
die($code);


This code will execute CSI 6n, but I am not able to capture the response, it will always be printed out when php exits.

Answer Source

You have to make some provision for reading unbuffered input. Here is an example:

<?php
$term = trim(`stty -g`);
system("stty -icanon -echo");
fwrite(STDOUT, "\033[6n");
$code = trim (fread(STDIN,100) );
system("stty '" . $term . "'");
if ( sscanf($code, "\033[%d;%dR", $row, $col) == 2 ) {
    printf ("position %d,%d\n", $row, $col );
} elseif ( strlen ($code ) > 0 ) {
    printf ("unexpected %d-byte reply\n", strlen ($code ));
}
?>