Welcome Guest, Not a member yet? Register   Sign In
Simple Flashdata Code for PHP Sessions
#1

[eluser]Aea[/eluser]
I have a need in a project I'm current developing to have customizable flash data without the use the traditional flashdata functionality offered by the native session class (which otherwise is very nice) since I prefer to use $_SESSION[] instead of the referencing the session class, the way I see it, it's a needless call, since I'm relying on that class simply to mitigate session fixation. Thus I created the follow code...

Usage...
$_SESSION['key'] = 'My Data';
$_SESSION['key:hl'] = #PagesPersisted;

$_SESSION['key:hl'] can be set at any time, making a key act as flashdata at any time, and similarly by unset($_SESSION['key:hl']) you can revert it back to regular session data.

Code:
function _flash_countdown()
    {
        foreach ($_SESSION as $key => $value)
        {
            $search = $key.':hl';
            if (isset($_SESSION[$search]))
            {
                if ($_SESSION[$search] <= 0)
                {
                    unset($_SESSION[$key], $_SESSION[$search]);
                }
                else
                {
                    --$_SESSION[$search];
                }
            }
        }
    }

I wrote this very quickly, so if anybody has suggestions or potential problems to point out, feel free to. This code also runs quite efficiently, but I'm sure there are ways to optimize it further Smile
#2

[eluser]systemsos[/eluser]
Random idea from talking on IRC today for this.
Code:
$_SESSION['random_data_to_keep_forever'] = 'dazz';
$_SESSION['my_temp_data_1'] = array('keep-this-for', 5);
$_SESSION['my_temp_data_2'] = array('keep-this-also-for', 3);

foreach ($_SESSION as $key) {
    if (is_array($key)) {
        //So if it's an array, it must have the pages until we need to clear it
        if ($condition-page-view-now=0) {
            //Remove Session Key here
        }
        //Do code here to $pages - 1
    }
}
#3

[eluser]Aea[/eluser]
systemos, it does look like that code will work, but won't it require additional functions to switch between regular session data, flash data, or even update lifespan? I created a different version which doesn't do value assignments and I think it will be marginally more efficient...

Code:
function _flash_countdown()
    {
    $keys = array_keys($_SESSION);
    
        foreach ($keys as $key) // Confusing Variables, Surely you kid?
        {
            $search = $key.':hl';
            if (isset($_SESSION[$search]))
            {
                if ($_SESSION[$search] <= 0)
                {
                    unset($_SESSION[$key], $_SESSION[$search]);
                }
                else
                {
                    --$_SESSION[$search];
                }
            }
        }
    }




Theme © iAndrew 2016 - Forum software by © MyBB