colorizing php cli scripts

Gravatar
Posted by apokalyptik

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\r\n";
 
echo "\033[32mgreen\033[37m\r\n";
 
echo "\033[41;30mblack on red\033[40;37m\r\n";

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

8 Responses

  1. bamdad says:

    Hi
    i checked the code
    it doesn’t work
    this is the output that php returns without any color :

    C:\xampplite\php>php -f clicodes\test.php
    ←[31mred←[37m
    ←[32mgreen←[37m
    ←[41;30mblack on red←[40;37m

    C:\xampplite\php>

  2. Bogdan says:

    Please see the MilcovLib library, it does just that: http://milcovlib.sf.net/

    Bamdad, it doesn’t work under Windows, the original post specifically mentions bash.

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

  4. 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”;

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

  6. Don’t forget that you have to put double quotes around the text formatting string, if you dont do so, it will never be parsed as a “color”.

  7. peter_wall says:

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

    *added to favourites!

    Pete

  8. Roberto says:

    Wonderfull help. Thankyou very much.

    Best Regards

Trackback URL for this entry