Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm currently creating a new neat CLI library for PHP, and i'd like to figure out the width/height of the console it's running in.

I've tried many things like digging through $_ENV, exec("echo $COLUMNS"), etc, but no result, while if i type echo $COLUMNS or $ROWS in bash commandline, it neatly displays the value.

What do i need to do to access this value from PHP?

I'm using .sh scripts like this:

#!/usr/bin/php -q <?php  require_once('lib.commandline.php');   class HelloWorld extends CommandLineApp {    public function main($args) {         echo('O, Hai.');      }  } 

Update Final solution:

public function getScreenSize() {        preg_match_all("/rows.([0-9]+);.columns.([0-9]+);/", strtolower(exec('stty -a |grep columns')), $output);       if(sizeof($output) == 3) {         $this->settings['screen']['width'] = $output[1][0];         $this->settings['screen']['height'] = $output[2][0];       }     } 
like image 311
SchizoDuckie Avatar asked Feb 04 '10 21:02

SchizoDuckie


2 Answers

Another shell option that requires no parsing is tput:

$this->settings['screen']['width'] = exec('tput cols') $this->settings['screen']['height'] = exec('tput lines') 
like image 164
Dennis Williamson Avatar answered Sep 22 '22 10:09

Dennis Williamson


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

like image 44
Joe Koberg Avatar answered Sep 20 '22 10:09

Joe Koberg