astonishin
astonishin

Reputation: 37

Save Constant GET Variable In A Session

Can some explain to me the best way to store a $_GET variable in a session and the only way the sessions changes is when we verify the data the session is being change to is different from the GET variable.

Currently i have

 $tid = clean_get($_GET['tid']);

in a global file which is included on every page the problem with that is the value of $tid will be erased and not stored in a session like i want it to once the user is not on a page with $tid set in the url.

Upvotes: 0

Views: 357

Answers (3)

Michael Fenwick
Michael Fenwick

Reputation: 2494

I think what you are looking for is something like

session_start();
foreach ($_GET as $key=>$value) {
    $_SESSION['getValues'][$key] = clean_get($value);
}

This will store all the values in $_GET in the $_SESSION. To retrieve the values later, you just have to use $_SESSION['getValues']['tid'] after calling session_start().

Here I'm assuming that clean_get() is just something that formats and/or escapes data that came in from forms, so calling it on each value before sticking into the session will do all that cleaning when needed.

Note: only call session_start() once, and make sure you do so before doing anything with $_SESSION, otherwise you'll get error messages.

Upvotes: 0

Rajan Rawal
Rajan Rawal

Reputation: 6313

If you get $_GET['tid'] in url then set session again by that new value otherwise restore it from session. Thats it.

session_start();
$tid = (isset($_GET['tid']) && $_GET['tid']!="") ? clean_get($_GET['tid']) : $_SESSION['tid'];

Try this and tell me is it solved?

Upvotes: 3

Fluffeh
Fluffeh

Reputation: 33512

Use a function like isset() to see if it is being sent. Only then should you replace it:

if(isset($_GET['tid']))
{
    $tid = clean_get($_GET['tid'])
    // Do stuff to change session data.
}

Upvotes: 1

Related Questions