How to get linux console $COLUMNS and $ROWS from PHP cli?

喜夏-厌秋 提交于 2019-12-03 22:23:47

Another shell option that requires no parsing is tput:

$this->settings['screen']['width'] = exec('tput cols')
$this->settings['screen']['height'] = exec('tput lines')

Use the PHP ncurses_getmaxyx function.

ncurses_getmaxyx (STDSCR, $Height, $Width)

PREVIOUSLY:

http://php.net/manual/en/function.getenv.php

$cols = getenv('COLUMNS');
$rows = getenv('ROWS');

The "proper" way is probably to call the TIOCGSIZE ioctl to get the kernel's idea of the window size, or call the command stty -a and parse the results for rows and columns

$COLUMNS and $LINES is probably not being exported to your program. You can run export LINES COLUMNS before running your app, or you can get this information directly:

$fp=popen("resize", "r");
$b=stream_get_contents($fp);
preg_match("/COLUMNS=([0-9]+)/", $b, $matches);$columns = $matches[1];
preg_match("/LINES=([0-9]+)/", $b, $matches);$rows = $matches[1];
pclose($fp);

Maybe this link might be the answer, you could use the ANSI Escape codes to do that, by using the echo using the specific Escape code sequence, in particular the 'Query Device', which I found another link here that explains in detail. Perhaps using that might enable you to get the columns and rows of the screen...

I dunno, why one should ever need grep to parse stty output: it does have a separate option to report "the number of rows and columns according to the kernel".

One-liner, no error handling:

list($rows, $cols) = explode(' ', exec('stty size'));

One-liner, assume both rows/cols to be 0 in case of problems and suppress any error output:

list($rows, $cols) = explode(' ', @exec('stty size 2>/dev/null') ?: '0 0');

Environment variables can be found in the $_ENV super global variable.

echo $_ENV['ROWS'];

for instance.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!