[thelist] php sessions

Sven Göttner sven at goettner.de
Tue Oct 15 09:17:10 CDT 2002


> ... If that's the case, how would I set the value of this session variable by
> the user clicking on something?

Not so easy, but can be done.
Here you go:

<code>

/* start the session (no values registered yet, just the thing itself) */
session_start();

/**
* register the critical variable, even if no value yet
* Note there's no "$" on the variable, it's just the NAME
*/
session_register('lightcart');

/**
* Now the session "watches" this variable.
* The session management takes care, that when $lightcart in the
* script is changing, the new value is automatically updated as
* $HTTP_SESSION_VARS['lightcart'] AND RESTORED ON EACH
* PAGE THAT USES THE SESSION.
* That's the difference between $HTTP_SESSION_VARS['lightcart'] and $lightcart:
* The value of $lightcart get's lost at the end of the script, the session value is saved on the
* server and being restored whenever you call session_start();
*
* Note that there are now TWO variables called lightcart:
* 1) $HTTP_SESSION_VARS['lightcart']   ---> SESSIONVARIABLE
* 2) $lightcart   --->  ordinary variable in your script
*
* You can now change the session value by changing $lightcart in the script:
*/
$lightcart = 'lightbox';   // results in $HTTP_SESSION_VARS['lightcart'] having the value 'lightcart'
$lightcart = 'foo'          // $HTTP_SESSION_VARS['lightcart'] is now 'foo'

/**
* Now how to do this by clicking a link ?
* Append a GET - parameter to the link:
*/
<a href="script.php?lightcart=lightbox">Show lightbox</a>

/* Or to switch back: */
<a href="script.php?lightcart=cart">Show cart</a>

/**
* Here's what script.php does:
* start session, -> restore previous value of $HTTP_SESSION_VARS['lightcart'],
* which would here be 'foo'.
*/
session_start();

/**
* Make the GET-Parameter of the link that called script.php
* the new value of the session variable
*/
$lightcart = $HTTP_GET_VARS['lightcart'];

/**
* Now, since the session "watches" the variable $lightcart
* and it's value has changed, the value in the session will change, too.
* Check it:
*/
echo $HTTP_SESSION_VARS['lightcart'];

</code>

Hint:
If you run into trouble with this an you're running PHP >= 4.2.2,
read the manual carefully for the difference between $HTTP_SESSION_VARS
and $_SESSION.
Here: http://www.php.net/manual/en/ref.session.php


Greetz,
	Sven



More information about the thelist mailing list