CodeIgniter Forums
How to make this session variable loop when refreshing/revisiting homepage? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: How to make this session variable loop when refreshing/revisiting homepage? (/showthread.php?tid=53373)



How to make this session variable loop when refreshing/revisiting homepage? - El Forum - 07-21-2012

[eluser]term25[/eluser]
I would like to do something like this:

Each time a visitor refresh/visits my homepage a value of some session variable changes in the particular pattern.

When he visits the page for the first time, the variable will be created with the value 1.

Then when he refresh/visit of homepage the value change to 2.

After another refresh/visit of homepage the value change to 3.

With another refresh/visit of the homepage the value goes back to 1.

And the cycle goes on forever.

Then I need to access this sesion variable and use it in my php code, but this is another story.


How to make this session variable loop when refreshing/revisiting homepage? - El Forum - 07-21-2012

[eluser]rwestergren[/eluser]
You could use the built-in session library, and increment/decrement the value based on its current value. Something like this:

Code:
$this->load->library('session');

if($visit = $this->session->userdata('visits'))
{
    // Handle previous visits
    if($visit < 3)
    {
        // Increment visit number
        $visit++;
    }
    else if($visit == 3)
    {
        // Reset visit number
        $visit = 1;
    }    
    // Set new visit number
    $this->session->set_userdata('visits', 1);    
}
else
{
    // First visit, initially set the value to 1
    $this->session->set_userdata('visits', 1);
}



How to make this session variable loop when refreshing/revisiting homepage? - El Forum - 07-21-2012

[eluser]term25[/eluser]
Great, thanks a lot, I think it should be working. However, shouldn't this part:
Code:
// Set new visit number
$this->session->set_userdata('visits', 1);


look like this?:

Code:
// Set new visit number
$this->session->set_userdata('visits', $visit);



How to make this session variable loop when refreshing/revisiting homepage? - El Forum - 07-21-2012

[eluser]rwestergren[/eluser]
Oops, yeah that's a typo. You've got it right. No problem!