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


16 thoughts on “colorizing php cli scripts

  1. What I do is include this file:
    //file: terminalcolores.php
    //Bash Terminal Color Codes:
    $BLACK = "33[30m";
    $RED = "33[31m";
    $GREEN = "33[32m";
    $BROWN = "33[33m";
    $BLUE = "33[34m";
    $PURPLE = "33[35m";
    $CYAN = "33[36m";
    $LIGHTGREY = "33[37m";

    $DARKGREY = "33[1;30m";
    $LIGHTBLUE = "33[1;34m";
    $LIGHTGREEN = "33[1;32m";
    $LIGHTCYAN = "33[1;36m";
    $LIGHTRED = "33[1;31m";
    $LIGHTPURPLE = "33[1;35m";
    $YELLOW = "33[1;33m";
    $WHITE = "33[1;37m";

    $BLACKBACKGROUND = "33[40";
    $REDBACKGROUND = "33[41";
    $GREENBACKGROUND = "33[42";
    $YELLOWBACKGROUND = "33[43";
    $BLUEBACKGROUND = "33[44";
    $CYANBACKGROUND = "33[46";
    $WHITEBACKGROUND = "33[47";

    $COLOROFF = "33[0m";


    then I use it like this:

    echo "{$RED}this is some red text{$COLOROFF}";