Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding PHP in CSS

Tags:

css

php

I'm trying to create a variable background, where the image changes based on the time of day. This code I have USED to work, but I did something somewhere along the line and didn't notice that the functionality had broken. Can someone explain to me why this doesn't work?

<html>
<?php

    function day()
    {
        if ( $hour >= 6 && $hour <= 18 )
        {
        return 1;
        } else { return 0; }
    }

?>

<style type="text/css">

body
{

    background-image: url('<?php echo (day() ? 'images/day_sheep.jpg'
                                             : 'images/night_sheep.jpg'); ?>');
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-color: silver
}

a {text-decoration:none;}
a:link {color:#ff0000;}
a:visited {color:#0000FF;}
a:hover {text-decoration:underline;}

</style>

</html>
like image 785
Oso Avatar asked Dec 12 '22 20:12

Oso


2 Answers

Inside your function day(), $hour is unset. It will be treated as 0 in a numerical context, and if you enable reporting of notices, you will see notices warning you of an unset variable. Did it used to be a global variable? Did you remove code that set its value or declared it as global?

Edit: Also, on a point of style, I feel it would look neater to have an external CSS file like this:

body {
    background-position: 50% 50%;
    background-repeat: no-repeat;
    background-color: silver
}

body.day {
    background-image: url('images/day_sheep.jpg');
}

body.night {
    background-image: url('images/night_sheep.jpg');
}

and then you can get rid of the CSS section of your php script, but include the above CSS file, and you need only have the following:

<body class="<?php echo day() ? 'day' : 'night'; ?>">
like image 155
Hammerite Avatar answered Dec 23 '22 16:12

Hammerite


You never declare what $hour is.

<html>
<?php
    function day()
    {
        $hour = date('G');
        if ( $hour >= 6 && $hour <= 18 )
        {
        return 1;
        } else { return 0; }
    }

?>
... snip ...
like image 30
tplaner Avatar answered Dec 23 '22 16:12

tplaner