PHP CLI Colors – PHP Class Command Line Colors (bash) - Comment Page: 1

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. [inttf_post_ad1] PHP Class for Coloring PHP Command Line (CLI) Scripts Output <?php class Colors { private $foreground_colors = array(); private $background_colors = array(); public function __construct() { // Set up shell...

40 comments on “PHP CLI Colors – PHP Class Command Line Colors (bash) - Comment Page: 1

1 2
    1. […] View post: PHP Class for Coloring PHP Command Line (CLI) Scripts Output – PHP … […]

      Reply
    2. […] – Simple System Maintenance with PHP-CLI Command Line PHP (IBM) Running Daemons in PHP PHP Class for Coloring Command Line Output PHP Command Line Progress Bar Share and […]

      Reply
    3. 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!

      Reply
    4. BEST JOB !!!! Great thanks !!!!

      Reply
    5. 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

      Reply
    6. 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.

      Reply
      • 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:

        
         '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 string
                        public static function getColoredString($string, $foreground_color = null, $background_color = null) {
                                $colored_string = "";
        
                                // Check if given foreground color found
                                if ( isset(self::$foreground_colors[$foreground_color]) ) {
                                        $colored_string .= "\033[" . self::$foreground_colors[$foreground_color] . "m";
                                }
                                // Check if given background color found
                                if ( 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 names
                        public static function getForegroundColors() {
                                return array_keys(self::$foreground_colors);
                        }
        
                        // Returns all background color names
                        public static function getBackgroundColors() {
                                return array_keys(self::$background_colors);
                        }
                }
        

        Example usage:

        
        echo ColorCLI::getColoredString('Test');
        echo ColorCLI::getColoredString('Test', 'blue');
        echo ColorCLI::getColoredString('Test', null, 'blue');
        
        print_r(ColorCLI::getForegroundColors());
        print_r(ColorCLI::getBackgroundColors());
        
        Reply
        • 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.

          Reply
    7. 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?

      Reply
      • Hi Olivier,

        Could you take screenshot and post sample image?

        Reply
    8. 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));
      }

      Reply
      • As you can see light_green, light_blue, light_cyan, light_red are… bold ;)

        Reply
        • 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 text
          
          echo -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';
            do FG=${FGs// /}
            echo -en " $FGs \033[$FG  $T  "
            for BG in 40m 41m 42m 43m 44m 45m 46m 47m;
              do echo -en "$EINS \033[$FG\033[$BG  $T  \033[0m";
            done
            echo;
          done
          echo
          

          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. :)

          Reply
    9. 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!

      Reply
      • 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. :)

        Reply
    10. Thank you for this wonderful class :)

      Reply
    11. Thanks. Worked fine for me !

      Reply
    12. Thank you! Very useful class for me!

      Reply
    13. 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);
      }
      }

      Reply
      • The comment got cut off
        red(“Enter Launch Code”,”green”);
        **/

        Reply
        • Still getting cut off, oh well

          Reply
          • 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

            Reply
    14. I get raw color string instead of colors what is happening ? ex. “0;33” instead of color…

      Reply
      • Hi michal,

        Could you post output of following command on your shell where you try to run/use this code:

        
        ps -p $$
        
        Reply
1 2

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Close