PHP Command Line Interface (CLI) has not built-in coloring for script output, like example Perl language has (perldoc.perl.org/Term/ANSIColor.html). So I decided to make own class for adding colors on PHP CLI output. This class works only Bash shells. This class is easy to use. Just create new instance of class and call getColoredString function with string and foreground color and/or background color.
PHP Class for Coloring PHP Command Line (CLI) Scripts Output
<?phpclass Colors {private$foreground_colors=array();private$background_colors=array();publicfunction __construct(){// Set up shell colors$this->foreground_colors['black']='0;30';$this->foreground_colors['dark_gray']='1;30';$this->foreground_colors['blue']='0;34';$this->foreground_colors['light_blue']='1;34';$this->foreground_colors['green']='0;32';$this->foreground_colors['light_green']='1;32';$this->foreground_colors['cyan']='0;36';$this->foreground_colors['light_cyan']='1;36';$this->foreground_colors['red']='0;31';$this->foreground_colors['light_red']='1;31';$this->foreground_colors['purple']='0;35';$this->foreground_colors['light_purple']='1;35';$this->foreground_colors['brown']='0;33';$this->foreground_colors['yellow']='1;33';$this->foreground_colors['light_gray']='0;37';$this->foreground_colors['white']='1;37';$this->background_colors['black']='40';$this->background_colors['red']='41';$this->background_colors['green']='42';$this->background_colors['yellow']='43';$this->background_colors['blue']='44';$this->background_colors['magenta']='45';$this->background_colors['cyan']='46';$this->background_colors['light_gray']='47';}// Returns colored stringpublicfunction getColoredString($string,$foreground_color=null,$background_color=null){$colored_string="";// Check if given foreground color foundif(isset($this->foreground_colors[$foreground_color])){$colored_string.="\033[".$this->foreground_colors[$foreground_color]."m";}// Check if given background color foundif(isset($this->background_colors[$background_color])){$colored_string.="\033[".$this->background_colors[$background_color]."m";}// Add string and end coloring$colored_string.=$string."\033[0m";return$colored_string;}// Returns all foreground color namespublicfunction getForegroundColors(){returnarray_keys($this->foreground_colors);}// Returns all background color namespublicfunction getBackgroundColors(){returnarray_keys($this->background_colors);}}?>
Colors class basic usage examples
<?php// Create new Colors class$colors=new Colors();// Test some basic printing with Colors classecho$colors->getColoredString("Testing Colors class, this is purple string on yellow background.","purple","yellow")."\n";echo$colors->getColoredString("Testing Colors class, this is blue string on light gray background.","blue","light_gray")."\n";echo$colors->getColoredString("Testing Colors class, this is red string on black background.","red","black")."\n";echo$colors->getColoredString("Testing Colors class, this is cyan string on green background.","cyan","green")."\n";echo$colors->getColoredString("Testing Colors class, this is cyan string on default background.","cyan")."\n";echo$colors->getColoredString("Testing Colors class, this is default string on cyan background.",null,"cyan")."\n";?>
Output:
All Foreground and background colors printed
<?php// Create new Colors class$colors=new Colors();// Get Foreground Colors$fgs=$colors->getForegroundColors();// Get Background Colors$bgs=$colors->getBackgroundColors();// Loop through all foreground and background colors$count=count($fgs);for($i=0;$i<$count;$i++){echo$colors->getColoredString("Test Foreground colors",$fgs[$i])."\t";if(isset($bgs[$i])){echo$colors->getColoredString("Test Background colors",null,$bgs[$i]);}echo"\n";}echo"\n";// Loop through all foreground and background colorsforeach($fgsas$fg){foreach($bgsas$bg){echo$colors->getColoredString("Test Colors",$fg,$bg)."\t";}echo"\n";}?>
Thank you for the tip! I admit it never occurred to me to color command line output but you got me thinking now! Many times you have to stare at multi-line outputs of some long running scripts and it’s oh so easy to miss an important line with some sort of an error or warning message in it. It would stand out so much more if it’s, say, red or black on yellow background. I think I’m going to give it a try now.
Thanks!
Thanks for this. Like @Scriptster, I’m going to use it for important debug messages/output. I’ve re-written it a bit to shorten the syntax, so to make the text red for example, I use
$c = new Colors();
$c->red(“I’m red”);
$c->green(“I’m green”);
I found your version a little over complicated so I simplified it and saved it as a Github Gist here – https://gist.github.com/1315354
There was no real need to require an instance as there are no local members being modified – so its purposely suited to just being accessed from the static state.
I checked your static function and idea is nice, but it lacks a few things.
1. It’s working only with PHP >= 5.3.0
2. It throws a PHP Notice if background color is not set
3. You have to call some totally random static method if you don’t want any foreground color
Static and much more compatible with earlier PHP versions example could be following:
<?phpclass ColorCLI {
static $foreground_colors=array('black'=>'0;30','dark_gray'=>'1;30','blue'=>'0;34','light_blue'=>'1;34','green'=>'0;32','light_green'=>'1;32','cyan'=>'0;36','light_cyan'=>'1;36','red'=>'0;31','light_red'=>'1;31','purple'=>'0;35','light_purple'=>'1;35','brown'=>'0;33','yellow'=>'1;33','light_gray'=>'0;37','white'=>'1;37',);
static $background_colors=array('black'=>'40','red'=>'41','green'=>'42','yellow'=>'43','blue'=>'44','magenta'=>'45','cyan'=>'46','light_gray'=>'47',);// Returns colored stringpublic static function getColoredString($string,$foreground_color=null,$background_color=null){$colored_string="";// Check if given foreground color foundif(isset(self::$foreground_colors[$foreground_color])){$colored_string.="\033[".self::$foreground_colors[$foreground_color]."m";}// Check if given background color foundif(isset(self::$background_colors[$background_color])){$colored_string.="\033[".self::$background_colors[$background_color]."m";}// Add string and end coloring$colored_string.=$string."\033[0m";return$colored_string;}// Returns all foreground color namespublic static function getForegroundColors(){returnarray_keys(self::$foreground_colors);}// Returns all background color namespublic static function getBackgroundColors(){returnarray_keys(self::$background_colors);}}
I never saw your reply and accidentally stumbled on this googling what else was out there just now :-)
If you recheck the gist here – https://gist.github.com/1315354
I’ve since fixed many of the complaints, added blink, underline, normal and some other things. It still uses __callStatic, but seriously, 5.4 is out, there’s no excuse to still be on 5.2. The bell function doesn’t belong honestly, but I’m working on a more generic general terminal control class, which I’ve used to implement for instance progress bars and other cool stuff, its not done yet though so I haven’t published it yet as some of the code is admittedly wonky.
Oh, I see what you mean, this depends on terminal what you are using. This “light blue” try to tell only color tone, not font weight. You can see all available command line colors with using following script (originally from http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html):
#!/bin/bash## This file echoes a bunch of color codes to the # terminal to demonstrate what's available. Each # line is the color code of one forground color,# out of 17 (default + 16 escapes), followed by a # test use of that color on all nine background # colors (default + 8 escapes).#T='gYw'# The test textecho-e"\n 40m 41m 42m 43m\
44m 45m 46m 47m";
for FGs in' m'' 1m'' 30m''1;30m'' 31m''1;31m'' 32m' \
'1;32m'' 33m''1;33m'' 34m''1;34m'' 35m''1;35m' \
' 36m''1;36m'' 37m''1;37m';
doFG=${FGs// /}echo-en" $FGs \033[$FG$T "for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
doecho-en"$EINS \033[$FG\033[$BG$T \033[0m";
doneecho;
doneecho
Blue is 34m and “light blue” is 1;34m. If you change another virtual console (ALT+F2 / ALT+F3 … or CTRL+ALT+F2 / CTRL+ALT+F3 …) and run above script then you might see same “light blue” with normal font weight. I tested it on Debian Sid and both blue and light blue is rendered exactly same font weight and 34m is much darker than 1;34m. I hope this helps you. :)
I have not even thought this, before you asked it. I guess that nowadays terminals, like gnome-terminal, konsole, lxterm, etc. renders these “light colors” with bold font weight, because it stands out more or some another good reason. :)
Thank you for the tip! I admit it never occurred to me to color command line output but you got me thinking now! Many times you have to stare at multi-line outputs of some long running scripts and it’s oh so easy to miss an important line with some sort of an error or warning message in it. It would stand out so much more if it’s, say, red or black on yellow background. I think I’m going to give it a try now.
Thanks!
BEST JOB !!!! Great thanks !!!!
Thanks for this. Like @Scriptster, I’m going to use it for important debug messages/output. I’ve re-written it a bit to shorten the syntax, so to make the text red for example, I use
$c = new Colors();
$c->red(“I’m red”);
$c->green(“I’m green”);
Cheers,
Ben
I found your version a little over complicated so I simplified it and saved it as a Github Gist here – https://gist.github.com/1315354
There was no real need to require an instance as there are no local members being modified – so its purposely suited to just being accessed from the static state.
Hi Jesse,
I checked your static function and idea is nice, but it lacks a few things.
1. It’s working only with PHP >= 5.3.0
2. It throws a PHP Notice if background color is not set
3. You have to call some totally random static method if you don’t want any foreground color
Static and much more compatible with earlier PHP versions example could be following:
Example usage:
I never saw your reply and accidentally stumbled on this googling what else was out there just now :-)
If you recheck the gist here – https://gist.github.com/1315354
I’ve since fixed many of the complaints, added blink, underline, normal and some other things. It still uses __callStatic, but seriously, 5.4 is out, there’s no excuse to still be on 5.2. The bell function doesn’t belong honestly, but I’m working on a more generic general terminal control class, which I’ve used to implement for instance progress bars and other cool stuff, its not done yet though so I haven’t published it yet as some of the code is admittedly wonky.
As for me (Ubuntu 10.04), all “light_xx” options are in bold (= the opposite of what the name suggests).
I’m pretty sure this is the default Ubuntu 10.04 shell.
Am I the only one?
Hi Olivier,
Could you take screenshot and post sample image?
Hi,
Here’s my screenshot:
And here’s the sample code I’ve used:
require_once 'includes/objet/cli_colors.php';
$cli = new CliColors();
$fg = array(
'bold',
'dim',
'black',
'dark_gray',
'blue',
'light_blue',
'green',
'light_green',
'cyan',
'light_cyan',
'red',
'light_red',
'purple',
'light_purple',
'brown',
'yellow',
'light_gray',
'white',
'normal'
);
$bg = array(
'black',
'red',
'green',
'yellow',
'blue',
'magenta',
'cyan',
'light_gray'
);
reset($bg);
list(,$bg_1)=each($bg);
list(,$bg_2)=each($bg);
list(,$bg_3)=each($bg);
list(,$bg_4)=each($bg);
printf("\n");
foreach ($fg as $fg_color) {
printf("[%'--50s]", $cli->getColoredString("Bg = ".$bg_1.", Fg = ".$fg_color, $fg_color, $bg_1));
printf("[%'--50s]", $cli->getColoredString("Bg = ".$bg_2.", Fg = ".$fg_color, $fg_color, $bg_2));
printf("[%'--50s]", $cli->getColoredString("Bg = ".$bg_3.", Fg = ".$fg_color, $fg_color, $bg_3));
printf("[%'--50s]\n", $cli->getColoredString("Bg = ".$bg_4.", Fg = ".$fg_color, $fg_color, $bg_4));
}
list(,$bg_1)=each($bg);
list(,$bg_2)=each($bg);
list(,$bg_3)=each($bg);
list(,$bg_4)=each($bg);
printf("\n");
foreach ($fg as $fg_color) {
printf("[%'--50s]", $cli->getColoredString("Bg = ".$bg_1.", Fg = ".$fg_color, $fg_color, $bg_1));
printf("[%'--50s]", $cli->getColoredString("Bg = ".$bg_2.", Fg = ".$fg_color, $fg_color, $bg_2));
printf("[%'--50s]", $cli->getColoredString("Bg = ".$bg_3.", Fg = ".$fg_color, $fg_color, $bg_3));
printf("[%'--50s]\n", $cli->getColoredString("Bg = ".$bg_4.", Fg = ".$fg_color, $fg_color, $bg_4));
}
Sorry, the screenshot can be found here:
http://olivierpons.fr/img/php_cli_colors.png
As you can see light_green, light_blue, light_cyan, light_red are… bold ;)
Oh, I see what you mean, this depends on terminal what you are using. This “light blue” try to tell only color tone, not font weight. You can see all available command line colors with using following script (originally from http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html):
Blue is 34m and “light blue” is 1;34m. If you change another virtual console (ALT+F2 / ALT+F3 … or CTRL+ALT+F2 / CTRL+ALT+F3 …) and run above script then you might see same “light blue” with normal font weight. I tested it on Debian Sid and both blue and light blue is rendered exactly same font weight and 34m is much darker than 1;34m. I hope this helps you. :)
Ok I’ve got it!
“lighter” in the sense of “color tone, not font weight”.
This is just a coincidence that all “lighter colors” are drawn with “bold fonts”, but there’s no relation between each other.
Ok!
I have not even thought this, before you asked it. I guess that nowadays terminals, like gnome-terminal, konsole, lxterm, etc. renders these “light colors” with bold font weight, because it stands out more or some another good reason. :)
Thank you for this wonderful class :)
Thanks. Worked fine for me !
Thank you! Very useful class for me!
Using __call(), i was able to shorten this a little
red("Enter Launch Code","green");
**/
class c {
public $foreground_colors = array();
public function __construct() {
// Set up shell colors
$this->foreground_colors['black'] = '0;30';
$this->foreground_colors['dark_gray'] = '1;30';
$this->foreground_colors['blue'] = '0;34';
$this->foreground_colors['light_blue'] = '1;34';
$this->foreground_colors['green'] = '0;32';
$this->foreground_colors['light_green'] = '1;32';
$this->foreground_colors['cyan'] = '0;36';
$this->foreground_colors['light_cyan'] = '1;36';
$this->foreground_colors['red'] = '0;31';
$this->foreground_colors['light_red'] = '1;31';
$this->foreground_colors['purple'] = '0;35';
$this->foreground_colors['light_purple'] = '1;35';
$this->foreground_colors['brown'] = '0;33';
$this->foreground_colors['yellow'] = '1;33';
$this->foreground_colors['light_gray'] = '0;37';
$this->foreground_colors['white'] = '1;37';
$this->background_colors['black'] = '40';
$this->background_colors['red'] = '41';
$this->background_colors['green'] = '42';
$this->background_colors['yellow'] = '43';
$this->background_colors['blue'] = '44';
$this->background_colors['magenta'] = '45';
$this->background_colors['cyan'] = '46';
$this->background_colors['light_gray'] = '47';
}
// Returns colored string
public function __call($foreground_color, $args) {
$colored_string = "";
$string = $args[0];
if(!empty($args[1])) {
$background_color = $args[1];
}
// Check if given foreground color found
if (isset($this->foreground_colors[$foreground_color])) {
$colored_string .= "33[" . $this->foreground_colors[$foreground_color] . "m";
}
// Check if given background color found
if (!empty($background_color) && isset($this->background_colors[$background_color])) {
$colored_string .= "33[" . $this->background_colors[$background_color] . "m";
}
$colored_string .= $string . "33[0m";
return $colored_string;
}
}
$c = new c();
foreach ($c->foreground_colors as $color => $v) {
echo $c->$color($color)."\n";
}
foreach ($c->foreground_colors as $color => $v) {
foreach ($c->background_colors as $bg_color => $v) {
echo $c->$color($color,$bg_color);
}
}
The comment got cut off
red(“Enter Launch Code”,”green”);
**/
Still getting cut off, oh well
That _construct is painful to look at!
Just do
class c {
private $foreground_colors = array(
'black' => '0;30';
'dark_gray' => '1;30';
'blue' => '0;34';
'light_blue' => '1;34';
'green' => '0;32';
'light_green' => '1;32';
'cyan' => '0;36';
'light_cyan' => '1;36';
'red' => '0;31';
'light_red' => '1;31';
'purple' => '0;35';
'light_purple' => '1;35';
'brown' => '0;33';
'yellow' => '1;33';
'light_gray' => '0;37';
'white' => '1;37';
);
... class stuff
I get raw color string instead of colors what is happening ? ex. “0;33″ instead of color…
Hi michal,
Could you post output of following command on your shell where you try to run/use this code: