47

How do I enable the colors for output of CLI? The below one is, running on Ubuntu.

enter image description here

If you see the screenshot, obviously the colors is enabled for terminal. And, if I call echo, it doesn't colorize the result, but if I use echo -e, it colorizes.
I checked manual page of echo, and -e means enable interpretation of backslash escapes
How can I enable this option for PHP CLI?

Barbayar Dashzeveg
  • 647
  • 1
  • 7
  • 11

4 Answers4

122

First we use an escape character so we can actually define a output color. This is done with \033 (\e). Then we open the color statement with [31m. Red in this case.

The "some colored text" will be the text outputted in a different color. And after that we have to close the color statement with \033[0m.

php -r 'echo "\033[31m some colored text \033[0m some white text \n";'

ref 1

ref 2

enter image description here

jayxhj
  • 2,829
  • 1
  • 19
  • 24
  • 1
    yes, it worked after I replaced `\e` with `033`. Thank you. – Barbayar Dashzeveg Dec 02 '15 at 04:33
  • 1
    and you can learn more [here](https://wiki.archlinux.org/index.php/Color_Bash_Prompt) – jayxhj Dec 02 '15 at 05:31
  • Or do not rely on `echo`'s sequences, and instead directly generate the ANSI sequences within the string using ANSI-C quoting: `$'\e[31mblah blah\e[0m`. This way you don't need to remember `\033` or whatever. – 4ae1e1 Dec 02 '15 at 06:21
  • 6
    single quotes will not work by the way :) use double quotes – İsmail Atkurt Nov 02 '17 at 17:02
  • 2
    +1 super helpful. FYI if anyone else needs [help looking up color codes](https://www.shellhacks.com/bash-colors/). – twknab May 28 '19 at 22:51
  • any way to get this to work when a PHP script is run via tty? Works from CLI normally but not in any git bash instances running in embedded terminals. (other commands show colours tho in the same setup) – Brad Aug 28 '20 at 16:17
  • `NOTE²: The “\e[0m” sequence removes all attributes (formatting and colors). It can be a good idea to add it at the end of each colored text. ;)` - if you don't close it everything you output afterwards - even different `echo` will still be in last color. – jave.web May 12 '23 at 12:10
24

For lazier

function colorLog($str, $type = 'i'){
    switch ($type) {
        case 'e': //error
            echo "\033[31m$str \033[0m\n";
        break;
        case 's': //success
            echo "\033[32m$str \033[0m\n";
        break;
        case 'w': //warning
            echo "\033[33m$str \033[0m\n";
        break;  
        case 'i': //info
            echo "\033[36m$str \033[0m\n";
        break;      
        default:
        # code...
        break;
    }
}
Giangimgs
  • 952
  • 1
  • 12
  • 16
9

After doing some experiments, I made these codes:

function formatPrint(array $format=[],string $text = '') {
  $codes=[
    'bold'=>1,
    'italic'=>3, 'underline'=>4, 'strikethrough'=>9,
    'black'=>30, 'red'=>31, 'green'=>32, 'yellow'=>33,'blue'=>34, 'magenta'=>35, 'cyan'=>36, 'white'=>37,
    'blackbg'=>40, 'redbg'=>41, 'greenbg'=>42, 'yellowbg'=>44,'bluebg'=>44, 'magentabg'=>45, 'cyanbg'=>46, 'lightgreybg'=>47
  ];
  $formatMap = array_map(function ($v) use ($codes) { return $codes[$v]; }, $format);
  echo "\e[".implode(';',$formatMap).'m'.$text."\e[0m";
}
function formatPrintLn(array $format=[], string $text='') {
  formatPrint($format, $text); echo "\r\n";
}

//Examples:
formatPrint(['blue', 'bold', 'italic','strikethrough'], "Wohoo");
formatPrintLn(['yellow', 'italic'], " I'm invicible");
formatPrintLn(['yellow', 'bold'], "I'm invicible");

Just copy and paste the code above and... Enjoy :)

Fandi Susanto
  • 2,272
  • 1
  • 26
  • 25
1

A Cleaner solution in the form a reusable class.

PHP Class:

class CLI
{

    // this method requires one variable. the second, color, is optional
    function cout_color($content, $color=null)
    {
        
        // if a color is set use the color set.
        if(!empty($color))
        {
            // if our color string is not a numeric value
            if(!is_numeric($color))
            {
                    //lowercase our string value.
                    $c = strtolower($color);
                
            }
            else
                {   
                    // check if our color value is not empty.
                    if(!empty($color))
                    {
                        
                        $c = $color;
                    
                    }
                    else
                        { 
                            // no color was set so lets pick a random one...
                            $c = rand(1,14);
                            
                        }
                    
                }
                
        }
        else    // no color argument was passed, so lets pick a random one w00t
            { 
                
                $c = rand(1,14);
                            
            }
        
        $cheader = '';
        $cfooter = "\033[0m";
        
        // let check which color code was used so we can then wrap our content.
        switch($c)
        {
                    
            case 1:
            case 'red':
                
                // color code header.
                $cheader .= "\033[31m";

            break;
            
            case 2:
            case 'green':
                
                // color code header.
                $cheader .= "\033[32m";

            break;

            case 3:
            case 'yellow':
                
                // color code header.
                $cheader .= "\033[33m";

            break;
            
            case 4:
            case 'blue':
                
                // color code header.
                $cheader .= "\033[34m";

            break;
            
            case 5:
            case 'magenta':
                
                // color code header.
                $cheader .= "\033[35m";

            break;
            
            case 6:
            case 'cyan':
                
                // color code header.
                $cheader .= "\033[36m";

            break;
            
            case 7:
            case 'light grey':
                
                // color code header.
                $cheader .= "\033[37m";

            break;
            
            case 8:
            case 'dark grey':
                
                // color code header.
                $cheader .= "\033[90m";

            break;
            
            case 9:
            case 'light red':
                
                // color code header.
                $cheader .= "\033[91m";

            break;
            
            case 10:
            case 'light green':
                
                // color code header.
                $cheader .= "\033[92m";

            break;
            
            case 11:
            case 'light yellow':
                
                // color code header.
                $cheader .= "\033[93m";

            break;
            
            case 12:
            case 'light blue':
                
                // color code header.
                $cheader .= "\033[94m";

            break;
            
            case 13:
            case 'light magenta':
                
                // color code header.
                $cheader .= "\033[95m";

            break;
            
            case 14:
            case 'light cyan':
                
                // color code header.
                $cheader .= "\033[92m";

            break;
            
        }
          
        // wrap our content.
        $content = $cheader.$content.$cfooter;
        
        //return our new content.
        return $content;
        

    }
      
     

}

Basic Usage:

//create a new object
$cli = new CLI();

//example string
$text = 'Success!';

//color via class color id
$text = $cli->cout_color($text, 2);

//color via string name
//$text = $cli->cout_color($text, 'green');

//for random color, ignore the second parameter.:
//$text = $cli->cout_color($text);

echo $text;

Modify to your project requirements. Good luck.

Miguel V.
  • 43
  • 5