Search code examples
phpwhile-loopsleep

Dynamically changing website background after certain time using php


Hi i am trying to change my webpage background after certain time using php here i tried using while loop but its not working neither showing any error. thanks for helping me

<?php
function random_color_part() {
    return str_pad( dechex( mt_rand( 0, 255 ) ), 2, '0', STR_PAD_LEFT);
}

function random_color() {
    return random_color_part() . random_color_part() . random_color_part();
}


function final_done(){
    $yourcolor = random_color();

    $styleBlock = sprintf('<style type="text/css">
            body{
                background-color:%s;
            }',$yourcolor);
    echo $styleBlock;

}
while (true) {
    final_done();
    sleep(3);
}
?>

Solution

  • There might be a confusion here: php is supposed to be on a server side, while your are using it to define a HTML data, which is used on the client side.

    The way you are using it should be done in a client side language, like javascript. The way it is programatically thought is good, but confused in a client/server schema.

    So you basically have two ways to do it:

    • The "normal one", using javascript to make the same loop changing background color.
    • The "php one", which sould not be recommended, in which you can define background color on each page load. Note that this one won't allows you to use a timed loop on client side.