Method to use php variables to interact with color

I’m relatively new to PHP/HTML so i’d like to know the best way to go about this scenario.

Say I have a variable $color.
color can either be
$color = “blue”;
$color = “red”;
based on users input.

When displaying it in html:

<?php echo($color); ?>

how can I make it change color in html CSS/style based on what the variable is. (I want it to be in blue font if the variable is equal to “blue” and vice versa.)
I know how to change font colors in html and all the basic style/css just like to know how you would go about changing it based on a string in a variable.

Basicly it is very easy.

<h1 style="color: <?php echo $color; ?>;">My Header</h1>

The only problem is that not just any php value is a valid color. You could write some validation code to check if the user input is valid. If the user may enter a hexadecimal color code or a valid CSS color then you could make a white list for the css colors and if the color that is entered by the user is not in the list and not a valid hexadecimal color code you could refuse the input.

Another problem that could occur is that background and text color are nearly the same color making the text unreadable. You could make a contrast calculation for this

Sponsor our Newsletter | Privacy Policy | Terms of Service