开发者

How to prevent a started PHP session from writing?

I have a situation where I've started a session with:

session_id( $consistent_session_name_for_user );
session_start();
$_SESSION['key'] = $value;

but then later I decide I don't actually want to "commit" (write) this session. PHP doesn't seem to have any kind of session_abort_write() function. I don't want to destroy the session variables from prior script runs, so I can't use session_destroy()

I tried session_id(""), but that call fails. I could "redirect" the session so it writes to another session, like session_id("trash"), but that would cause a lot of PHP (Apache) connections to try to write to the same session "file", which I want to avoid.

I'm high开发者_Python百科ly simplifying the problem here, we're actually storing sessions in Memcached and this is a complex codebase. So I don't want to be sending unnecessary "trash" sessions to the Memcached server all the time.


From PHP.net,
session_regenerate_id will replace the current session id with a new one, and keep the current session information.

session_unset will free all registered variables
session_unregister ( string $name ) will unregister a specific variable


I haven't actually determined if this method prevents writing the session to the session store, but here's the solution I finally used:

session_id( 'trash' ); // or call session_regenerate_id() as someone else suggested
$_SESSION = array(); // clear the session variables for 'trash'.

I'm hoping this has the effect that nothing will get written, but I'm guessing it still will write a blank file, because PHP can't know that sess_trash isn't already there.

If you want to completely avoid writing the session, you'll have to use a custom session handler in PHP and set a global flag to prevent writing the session.


You could probably use something with session_set_save_handler to put dummy functions in for session handling.

<?php
function fakeIt() {
    return true;
}
session_set_save_handler("fakeIt", "fakeIt", "fakeIt", "fakeIt", "fakeIt", "fakeIt");


There is session_write_close(). It dumps out the session array to storage and then "closes" it - $_SESSION will still be available and read/writeable, but any changes will no longer be saved, unless you do a session_start() again later on within the script.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜