tags:

views:

76

answers:

7

What is the easiest way to set background color in PHP ?

+2  A: 

You must use CSS. Can't be done with PHP.

Jay
It can be done.
Dan
PHP would just change the CSS (or HTML, but that wouldn't be right), not the background color itself...
alcuadrado
I would've given you an upvote, since using CSS is definitely the way to go in this situation, but I'm not really a fan of the sentence *Can't be done*. To sum it up for ion, just use CSS; PHP is the wrong tool for this, unless you have a specific case where it's indispensable, e.g. you have to read the colors from a database.
Giu
+2  A: 
<?php
    header('Content-Type: text/css');
?>

some selector {
    background-color: <?php echo $my_colour_that_has_been_checked_to_be_a_safe_value; ?>;
}
David Dorward
A: 

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

code-zoop
A: 

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

hollsk
A: 

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 ?>;
}
Dan
here goes XSS...
Col. Shrapnel
Do you see the comment where it says //Few checks ? By that I ment sanitize the input.
Dan
Although you are right, should have been clear. I apologize if I confused the op.
Dan
look the whole approach is wrong. you cannot actually deal with colors in PHP. you have to determine some TEXT to output and than make PHP output it. But text itself is your choice, not PHP's. You cannot change colors with PHP, you can only output texts. It is HTML/CSS question, not PHP. Not to mention we do not know WHAT background we're working on - a picture, a whole HTML page, a some div.
Col. Shrapnel
well if i can't than i can't, i will just use html color
ion
A: 

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.

Mike Johnson
A: 

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.

Centurion