0

I want to use sessions in a plugin, I use this code in my plugin to start a session

add_action('init','register_session',1);
function register_session(){
    global $cons;
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    if (isset($_GET['abc'])){
        $_SESSION['abcd'] = $_GET['abc'];
    }
}

The session variable works even after a page reload where the GET is not set but then the session seams to be destroyed. I am also geting this warning from my plugin php file

PHP Warning:  session_start(): Cannot start session when headers already sent in

Is there an alternative way to store session data or make sessions work? I have seen some plugins but I would prefer to not use them. Also I have seen this answer and it doen't work for me

EDIT: The session seems to be active always but the session variable is reseted after 2 different page loads

7
  • You mean fuxia's template_redirect answer? You really shouldn't be getting 'headers already sent' then. What's the code in the warning that's sent output before that? – Rup May 10 at 23:03
  • It's just the same warning from previous page loads – George Viennas May 10 at 23:06
  • And that's the complete text of the warning "Cannot start session when headers already sent in" ? It doesn't give you a filename and a line e.g. /wp-content/plugins/something/ or /wp-content/themes/ that you can use to work out where the first output is? I suppose you could pick an earlier hook instead. – Rup May 10 at 23:08
  • Yes there is a path to my plugin after the warning, the path is /home/497655.cloudwaysapps.com/emgkpuhbhv/public_html/wp-content/plugins/lw-for-woocommerce/wc-lw.php on line 22 . What is an earlier hook than init? – George Viennas May 10 at 23:11
  • I can't find that plugin to see what it's doing, I guess it's not public. If you said you've already tried template_redirect instead of init and that didn't fix it, then I guess you could try after_setup_theme or even plugins_loaded, but I'd look at your lw-for-woocommerce plugin and work out what the action handler is on line 22 of that file and what it's doing: it really ought not be outputting anything before template_redirect, and that feels like the right one to use to me. – Rup May 10 at 23:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.