I'm pretty new to PHP, and I'm designing a site that needs to do the following:

  • Select randomly from a series of about 5 different background images
  • Store the selected image name in a session variable (so that the user has the same background image on every page)

I'm pretty sure that I can setup it's selecting randomly from images and storing it in a session variable. The thing I can't figure out is how I should execute it most efficiently. Will it work to do a php file include of the php file that has the code? Also, I'm not sure how to make it so that the page pulls the session variable and sets that image as the background.

Any suggestions? Thanks,

  • Josh

    To get you started:

    <?
    if(!isset($_SESSION['background'])) {
      $_SESSION['background'] = 'background'.(mt_rand(1, 5)).'.jpg';
    }
    ?>
    <html>
    <head>
    <style>
    body {
     background-image: url(<?php echo $_SESSION['background']?);
    }
    </style>
    </head>
    <body>
    ...
    </body>
    </html>
    

      Thanks mjax. My main problem though is figuring out how to use one php file to include and have it check to make sure there is a session varible set, and if it is, to display the image in the background of a specified <div>.

        All you have to do, is to take the code below and save it to a file (ex, background.php)

        <?php
        session_start();
        
        if(!$_SESSION['background'])
        $_SESSION['background'] = 'background' . mt_rand(1, 5). '.jpg';
        ?>

        and then to include it in your other PHP files, you can do something like this:

        <?php
        session_start();
        include('background.php')
        
        ... rest of your code
        ?>

        and then in your special <div>, you could do something like this: (or as mjax suggested)

        <div style="background: url(<?=$_SESSION['background'];?>);">bla bla...</div>
          Write a Reply...