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

How to Make Google Chrome Forget a Permanent HTTP 301 Redirect

Finding and Fixing Unintended Body Overflow to Remove Horizontal Scrollbars

Responsive Logo Design Overview

How to Disable Open File Security Warnings on Windows by File Type

View all posts


All Posts Categories

Business Cheat Sheets CLI Design Development Downloads Drupal Email Google Apps HID Keyboards Multilingualism Open Source Philosophy PHP Pointing Devices Productivity Quotes Science Security SEO Technology Thoughts Windows Zend Framework