views:

26

answers:

2

Hi,

I've searched the web but haven't been able to find a solution to the following challenge:

I'd like to somehow associate a function that executes when session_start is called independent of the page session_start is called in. The function is intended to restore constants I've stored in $_SESSION using get_defined_constants() so that they're available again to any PHP page.

This seems so straightforward to me but I'm pretty sure the PHP Session extension doesn't support the registration of user-defined events. I was wondering if anyone might have insight into this issue so I can either figure out the solution or stop trying.

Ideally, I'd like to just register the function at run-time like so:

$constants = get_defined_constants();

$_SESSION["constants"] = $constants["user"];

function event_handler () {
    foreach ($_SESSION["constants"] as $key => $value) {
        define($key, $value);
    }
}

register_handler("session_start", "event_handler");

So in any webpage, I could just go:

session_start();

and all my constants would be available again.

Any help would be greatly appreciated.

+2  A: 

What you are looking for is session_set_save_handler(). Although the functionality isn't as granular as you desire, it does fit the bill.

Adrian
I thought about this but couldn't see how you append the sesson_start routine. I don't want to overwrite it and setup my own handlers (ie: not interested in changing the way storage is implemented) - I just wanted to tack on some extra code so to speak. Could you point me to an example of how I can use session_set_save_handler to do this without affecting how storage is implemented?
A: 

Besides of using your own session handle, you could also use a class to store the constants in, store that object in the session and use the magic method __wakeup to write the constants when the constants object is rebuild on session_start.

Gumbo