Generating Command Line Colors with PHP
January 10, 2012

Introduction

Generating ANSI (or ASCII) command line colors, or terminal colors, or whatever you call them, is easy with PHP. As I have said in my previous post, ANSI Command Line Colors under Windows, having colored text in the command line is a great help for spotting error or success messages. So here’s a quick and dirty function in PHP to do just that.

The PHP Function


<?php

function colorize($text, $status) {
 $out = "";
 switch($status) {
  case "SUCCESS":
   $out = "[42m"; //Green background
   break;
  case "FAILURE":
   $out = "[41m"; //Red background
   break;
  case "WARNING":
   $out = "[43m"; //Yellow background
   break;
  case "NOTE":
   $out = "[44m"; //Blue background
   break;
  default:
   throw new Exception("Invalid status: " . $status);
 }
 return chr(27) . "$out" . "$text" . chr(27) . "[0m";
}

echo colorize("Your command was successfully executed...", "SUCCESS");

References

http://en.wikipedia.org/wiki/ANSI_escape_code

http://php.net/manual/en/function.chr.php

https://wiki.archlinux.org/index.php/Color_Bash_Prompt


Development PHP CLI

Share this post


Written by
Mario Awad

Founder of SOFTKUBE, lead developer, and getting things done addict. Passionate about open source, user interface design, business development, and the tech world.

More about Mario Awad


About
SOFTKUBE

A small team of experts developing simple, usable, and high-quality web solutions. We blog about business, entrepreneurship, web development, and technology.

More about us


Recent Posts

Shared Office Space for Rent in Dekwaneh, Beirut, Lebanon as a Professional Work Environment

Transform your Custom PHP Script into a Globally Available CLI Command

Using Google for Live Unit Conversions

Declaring a Constant Array in PHP

View all posts


All Posts Categories

Business CLI Development Downloads Drupal Email Google Apps Multilingualism Open Source PHP Security SEO Technology Windows Zend Framework