Embedding PHP in CSS

I am trying to create a background variable where the image changes depending on the time of day. This code, which I used to work, but I did something somewhere along the line and did not notice that the functionality broke. Can someone explain to me why this is not working?

<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> 
+4
source share
2 answers

Inside your day() function, $hour not set. It will be treated as 0 in a numerical context, and if you turn on the notification report, you will see warnings warning you of an undefined variable. Was it a global variable? Did you delete the code that set its value or declared global?

Edit: Also, in style style, I believe that an external CSS file would look 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 only need to have the following:

 <body class="<?php echo day() ? 'day' : 'night'; ?>"> 
+12
source

You never declare what $ hour is.

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

All Articles