Random image per visit

I have a query to display a random background image

  SELECT *
    FROM page_backgrounds
ORDER BY RAND()

This is indeed gives me a random background image but as well when I go from page to page within the website. What I’m actually looking for is a way to have a random background per visit. What is the best way to do that?

Thank you in advance

I’d suggest you store the image that you’ve assigned as background in a session. Then it’s a matter of deciding when you make a session expire, and checking whether the user’s session has an existing background image, and if not, load a random one and assign it to the user’s session.

Hi Dharma. Thank you for your reaction. I tried the following:

I added this to the main controller

        $page_background      =  $this->page->get_page_backgrounds();
        $random_photo           =  $this->session->set('random_photo', $page_background['background']);
        $random_photo           =  $this->session->get('random_photo');

and then in the template:

<img src="/images/page_backgrounds/desktop/<?php echo $random_photo; ?>">

But I still get a changing image. Or is this the wrong approach?

From what I can see this code gets executed each page load, and I see no check whether the session variable for ‘random_photo’ exists. What you want is probably something like:

disclaimer: I do not know PHP, consider this pseudocode

function set_session_background () {
  $page_background =  $this->page->get_page_backgrounds();
  this->session->set('page_background', $page_background['background']);
  return $page_background['background'];
}

$background = $this->session->get('page_background') || set_session_background()

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.