views:

69

answers:

3

I'm making somewhat of a "module" that gets included into another unrelated PHP application. In my "module" I need to use sessions. However, I get the 'session has already been started...' exception. The application that my "module" is included into is starting the session. If I cannot disable sessions in this application, what are my options? I'd like to use Zend_Session, but it seems upon first glance that it is not possible. However, maybe there is another way? Any ideas?

Thanks!

+4  A: 

With PHP’s session implementation, there can only be one session at a time. You can use session_id to check if there currently is a session:

if (session_id() === '') {
    // no current session
}

Now if there is already an active session, you could end it with session_write_close, change the session ID’s name with session_name to avoid conflicts, start your session, and restore the old session when done:

$oldName = session_name();
if (session_id() !== '') {
    session_write_close();
}
session_name('APPSID');
session_start();

// your session stuff …

session_write_close();
session_name($oldName);
session_start();

The only problem with this is that PHP’s session implementation does only send the session ID of the last started session back to the client. So you would need to set the transparent session ID (try output_add_rewrite_var) and/or session cookie (see setcookie) on your own.

Gumbo
But then he must still be careful to not interfere with the session variables of the other application.
Alex
@GumboBut what if I want to start my session as such:$session = new Zend_Session_Namespace('session');
sims
@sims: Sorry, I’m not familiar with Zend_Session_Namespace.
Gumbo
+1  A: 

Try setting a custom "name" parameter for your application.

The default is PHPSESSID. You can change it to PHPSESSID_MYAPP to avoid conflicts with the other app.

Alex
A: 

add the following code before you want to use the Session feture:

@session_start();

etng
What does the at-mark (@) do?
sims
@Sims It is called `shut up operator`
takeshin
Ahh, that thing. I don't use that. And, it will not help since I'm not starting the session via session_start(); but via $session = new Zend_Session_Namespace('session');
sims