Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.6k views
in Technique[技术] by (71.8m points)

php - Handling session already started & set_cookie_params

I've seen lots of examples about how to detect if a PHP session is started. What I can't find is how to handle cookie params if one is started.

Here's my code. This is in a WordPress plugin. If another plugin starts the session, I get a warning about setting cookie params when this plugin runs. How do I correctly set these params if another plugin has already started a session without doing a session_destroy and goofing up the other plugin's session?

    $session_length = (60 * 60) * 8; // 1 hour x 8 = 8 hours
    session_set_cookie_params($session_length, "/", null, false, true);
    session_start();
    setcookie(session_name(), session_id(), time() + $session_length);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Overall your question -as currently put- seems too general. With the limited information you have given at this point I do not feel you should be dealing with the session generally unless you're sure you want to be the only one doing so.

Because $_SESSION is a global special case in PHP and because you state "This is in a WordPress plugin" you are always going to be an arbitary one-of-many plugin for dealing with a session that can be used/set/unset by any other of the one-of-many WordPress plugins that any WordPress admin can and will have loaded outside of your plugin's control.

Therefore:

You need to identify the $_SESSION has started already (with session_name()) to check if:

  • a) there's a session there already and then
  • b) if that session is your own

and act accordingly; in this case, destroy their session and then set your own with its own parameters.


And why the hell are you, in 2021, trying to set a session via a WordPress plugin with security = false?! THAT needs to be improved and updated before you do anything else.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.5k users

...