Set background color in PHP?
What is the easies开发者_StackOverflow社区t way to set background color in PHP ?
just insert the following line and use any color you like
echo "<body style='background-color:pink'>";
<?php
header('Content-Type: text/css');
?>
some selector {
background-color: <?php echo $my_colour_that_has_been_checked_to_be_a_safe_value; ?>;
}
You must use CSS. Can't be done with PHP.
CSS supports text input for colors (i.e. "black" = #000000 "white" = #ffffff) So I think the helpful solution we are looking for here is how can one have PHP take the output from an HTML form text input box and have it tell CSS to use this line of text for background color.
So that when a a user types "blue" into the text field titled "what is your favorite color", they are returned a page with a blue background, or whatever color they happen to type in so long as it is recognized by CSS.
I believe Dan is on the right track, but may need to elaborate for use PHP newbies, when I try this I am returned a green screen no matter what is typed in (I even set this up as an elseif to display a white background if no data is entered in the text field, still green?
You can use php in the style sheet. Just remember to set header("Content-type: text/css") in the style.php (or whatever then name is) file
This really depends on what you need to do. If you want to set a background colour on a page then you need to use CSS as per Jay's and David Dorward's answers.
If you are building an image with PHP then you can use the GD library to allocate colours yourself. I don't recommend this without thoroughly reading up on how to create images with GD. http://www.php.net/manual/en/function.imagecolorallocate.php
Try this:
<style type="text/css">
<?php include("bg-color.php") ?>
</style>
And bg-color.php can be something like:
<?php
//Don't forget to sanitize the input
$colour = $_GET["colour"];
?>
body {
background-color: #<?php echo $colour ?>;
}
You better use CSS for that, after all, this is what CSS is for. If you don't want to do that, go with Dorwand's answer.
I would recommend to use css, but php to use to set some class or id for the element, in order to make it generated dynamically.
精彩评论