Skip to content

Instantly share code, notes, and snippets.

@agarzon
Forked from bluefuton/cli_color.class.php
Last active December 18, 2015 05:19
Show Gist options
  • Save agarzon/5731895 to your computer and use it in GitHub Desktop.
Save agarzon/5731895 to your computer and use it in GitHub Desktop.
PHP Class for CLI Colors
<?php
// Based upon http://goo.gl/406o
class CliColor
{
private $colors = array();
private $bgcolors = array();
public function __construct()
{
// Set up shell colors
$this->colors['black'] = '0;30';
$this->colors['dark_gray'] = '1;30';
$this->colors['blue'] = '0;34';
$this->colors['light_blue'] = '1;34';
$this->colors['green'] = '0;32';
$this->colors['light_green'] = '1;32';
$this->colors['cyan'] = '0;36';
$this->colors['light_cyan'] = '1;36';
$this->colors['red'] = '0;31';
$this->colors['light_red'] = '1;31';
$this->colors['purple'] = '0;35';
$this->colors['light_purple'] = '1;35';
$this->colors['brown'] = '0;33';
$this->colors['yellow'] = '1;33';
$this->colors['light_gray'] = '0;37';
$this->colors['white'] = '1;37';
$this->bgcolors['black'] = '40';
$this->bgcolors['red'] = '41';
$this->bgcolors['green'] = '42';
$this->bgcolors['yellow'] = '43';
$this->bgcolors['blue'] = '44';
$this->bgcolors['magenta'] = '45';
$this->bgcolors['cyan'] = '46';
$this->bgcolors['light_gray'] = '47';
}
// Returns colored string
public function getColoredString($string, $color = null, $bgcolor = null)
{
if (!self::isCli())
{
return $string;
}
$coloredString = "";
// Check if given foreground color found
if (isset($this->colors[$color]))
{
$coloredString .= "\033[" . $this->colors[$color] . "m";
}
// Check if given background color found
if (isset($this->bgcolors[$bgcolor]))
{
$coloredString .= "\033[" . $this->bgcolors[$bgcolor] . "m";
}
// Add string and end coloring
$coloredString .= $string . "\033[0m";
return $coloredString;
}
// Returns all foreground color names
public function getForegroundColors()
{
return array_keys($this->colors);
}
// Returns all background color names
public function getBackgroundColors()
{
return array_keys($this->bgcolors);
}
// Are we running on the command line?
public static function isCli()
{
return (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR']));
}
}
$c = new CliColor;
echo $c->getColoredString('Hello World', 'red', 'yellow');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment