Sunday, July 26, 2009

PHP: Generate random color code

Hello! today I was surfing the net again reading up articles when I came across this website which has a few codes on several uses. but their snippets were quite full of flaws and vulnerability.

well, I am going to talk about one of their code snippets: http://phpsnips.com/snippet.php?id=34 - Generating random color code.

Here's mine, a function that generates CSS-compatible colour code in hexadecimal:
<?php

function rand_colorCode(){
$r = dechex(mt_rand(0,255)); // generate the red component
$g = dechex(mt_rand(0,255)); // generate the green component
$b = dechex(mt_rand(0,255)); // generate the blue component
$rgb = $r.$g.$b;
if($r == $g && $g == $b){
$rgb = substr($rgb,0,3); // shorter version
}
return '#'.$rgb;
}

$code = rand_colorCode();
echo 'This code is '.$code.'';

?>


Isn't this much better than the one posted at phpsnips.com? Note that this function doesn't utilize the functions in GD, but you can use the RGB in GD.

No comments: