Skip to content
PHP Logo

How can PHP be used to dynamically change the background image of a webpage based on the current time without causing performance issues?

To dynamically change the background image of a webpage based on the current time without causing performance issues, you can create an array of background images corresponding to different times of the day. Then, use PHP to determine the current time and select the appropriate background image to display on the webpage.

php
<?php
// Array of background images for different times of the day
$backgrounds = array(
    'morning' => 'morning.jpg',
    'afternoon' => 'afternoon.jpg',
    'evening' => 'evening.jpg',
    'night' => 'night.jpg'
);

// Get the current hour
$current_hour = date('G');

// Determine the time of the day
if ($current_hour >= 6 && $current_hour < 12) {
    $time_of_day = 'morning';
} elseif ($current_hour >= 12 && $current_hour < 18) {
    $time_of_day = 'afternoon';
} elseif ($current_hour >= 18 && $current_hour < 24) {
    $time_of_day = 'evening';
} else {
    $time_of_day = 'night';
}

// Set the background image based on the time of the day
$background_image = $backgrounds[$time_of_day];
?>

<!DOCTYPE html>
<html>
<head>
    <style>
        body {
            background-image: url('<?php echo $background_image; ?>');
            background-size: cover;
            background-repeat: no-repeat;
            height: 100vh;
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
    <!-- Your webpage content here -->
</body>
</html>