I'm making somewhat of a "module" that gets included into another unrelated PHP applicati开发者_开发技巧on. 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!
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.
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.
Add the following code before you want to use the Session feature:
@session_start();
精彩评论