by Klaus Graefensteiner
1. March 2010 16:00
PHP Color Attribute Picker
In this blog post I am showing a simple PHP form that lets the user enter a name and color attribute values for the foreground and background color of an html element.
Figure 1: Resulting web page of the web-safe color attribute value picker
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<?php
$name = '';
if (isset($_GET['name']))
{
$name = filter_input(INPUT_GET, 'name', FILTER_SANITIZE_SPECIAL_CHARS);
if ($name === false)
{
$name = "Not a valid name!\n";
}
}
$backgroundcolor = '';
if (isset($_GET['backgroundcolor']))
{
$backgroundcolor = filter_input(INPUT_GET, 'backgroundcolor',FILTER_VALIDATE_INT);
if ($backgroundcolor === false)
{
$backgroundcolor = "Not a valid background color!\n";
}
}
$foregroundcolor = '';
if (isset($_GET['foregroundcolor']))
{
$foregroundcolor = filter_input(INPUT_GET, 'foregroundcolor',FILTER_VALIDATE_INT);
if ($foregroundcolor === false)
{
$foregroundcolor = "Not a valid foregroundcolor color!\n";
}
}
function GetWebSafeColors()
{
$WebSaveColors = array();
$ArrayIndex = 0;
for($red = 0x0; $red <= 0xff; $red += 0x33)
{
for($green = 0x0; $green <= 0xff; $green += 0x33)
{
for($blue = 0x0; $blue <= 0xff; $blue += 0x33)
{
$WebSaveColors[$ArrayIndex++] = sprintf("#%02x%02x%02x", $red, $green, $blue);
}
}
}
return $WebSaveColors;
}
function RenderColorOptions($WebSafeColors)
{
while(list($value, $color) = each($WebSafeColors))
{
echo "<option value=\"$value\">$color</option>";
}
}
function RenderNameSpan($backgroundcolor, $foregroundcolor, $name)
{
$WebSafeColors = GetWebSafeColors();
echo "<p style=\"color:$WebSafeColors[$foregroundcolor]; background-color:$WebSafeColors[$backgroundcolor]; font-size:72px\">Hello $name, Welcome to my Great Site</p>";
}
?>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>webcolors.php</title>
</head>
<body>
<form method="GET" action="">
<label>Enter your name:</label>
<input type="text" name="name"></input>
<br />
<label>Select your background color:</label>
<select name="backgroundcolor" id="backgroundcolor">
<?php
RenderColorOptions(GetWebSafeColors());
?>
</select>
<br />
<label>Select your foreground color:</label>
<select name="foregroundcolor" id="foregroundcolor">
<?php
RenderColorOptions(GetWebSafeColors());
?>
</select>
<br />
<input type="submit" value="Submit">
</form>
<?php
if(isset($_GET['name']))
{
RenderNameSpan($backgroundcolor, $foregroundcolor, $name);
}
?>
</body>
</html>
Download
The entire script can be downloaded here: webcolors.zip
Ausblick
You gotta like PHP. It just flows.