colorizing php cli scripts

It’s pretty common in most scripting languages which center around the command line (bash, perl, etc) to find information on colorizing your shell script output, mainly because those languages are tied very tightly to command line use. It can be difficult, however, to find information about adding this same nice feature to a php cli script. The reason is simple: most people dont use php for cli applications; most cli programmers use something else. It’s not difficult to adapt the same techniques listed in most bash howtos (generally in the section reserved for colorizing your command prompt) for generating colored terminal output for php.

echo "\033[31mred\033[37m
";

echo "\033[32mgreen\033[37m
";

echo "\033[41;30mblack on red\033[40;37m
";

Simple, functional, useful (even if a bit complicated.) I leave it to you to lookup a bash prompt colorization howto to hunt down your own list of escape color codes (call it homework.)

Cheers

16 thoughts on “colorizing php cli scripts

  1. Hi

    i checked the code

    it doesn't work

    this is the output that php returns without any color :

    C:xampplitephp>php -f clicodestest.php

    ←[31mred←[37m

    ←[32mgreen←[37m

    ←[41;30mblack on red←[40;37m

    C:xampplitephp>

    • Chetan Sharma says:

      Add Spaces between the code
      ←[31m red←[37m

      ←[32m green←[37m

      ←[41;30m black on red←[40;37m

  2. Wes says:

    Do you know if it's possible to assign the color codes to variables and then use them? I have played with it for a while, and no luck…

    Any clues?

  3. Thomas says:

    Here is a list of the codes, condensed into variables you can just place in your strings: (I have the same thing for my bash scripts)

    //Terminal Colour Codes (BASH CODES)

    $BLACK="33[0;30m";

    $DARKGRAY="33[1;30m";

    $BLUE="33[0;34m";

    $LIGHTBLUE="33[1;34m";

    $GREEN="33[0;32m";

    $LIGHTGREEN="33[1;32m";

    $CYAN="33[0;36m";

    $LIGHTCYAN="33[1;36m";

    $RED="33[0;31m";

    $LIGHTRED="33[1;31m";

    $PURPLE="33[0;35m";

    $LIGHTPURPLE="33[1;35m";

    $BROWN="33[0;33m";

    $YELLOW="33[1;33m";

    $LIGHTGRAY="33[0;37m";

    $WHITE="33[1;37m";

  4. Thomas says:

    Ekkk, it left out some of the characters. There should be a backslash() and a zero (0) in front of each of those 33's.

  5. peter_wall says:

    Thanks for this reference, always nice to find exactly what your looking for!

    *added to favourites!

    Pete

Leave a Reply to peter_wallCancel reply