How to use session_start in Wordpress?

后端 未结 4 1197
悲哀的现实
悲哀的现实 2020-12-09 04:05

I\'m creating a bilingual site and have decided to use session_start to determine the language of the page using the following:

session_start();         


        
相关标签:
4条回答
  • 2020-12-09 04:10

    Based on this answer and the answers given here, it's best to use the following code snippets:

    For versions of PHP >= 5.4.0, PHP 7:

    function register_my_session() {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
    }
    add_action('init', 'register_my_session');
    

    Reference: http://www.php.net/manual/en/function.session-status.php


    For versions of PHP < 5.4.0:

    function register_my_session() {
        if(session_id() == '') {
            session_start();
        }
    }
    add_action('init', 'register_my_session');
    

    Reference: https://www.php.net/manual/en/function.session-id.php


    I don't want to take any credits, I just felt like sharing this information would be helpful.

    0 讨论(0)
  • 2020-12-09 04:25

    I found an interesting article by Peter here. I'm using the following code in my functions.php:

    add_action('init', 'myStartSession', 1);
    add_action('wp_logout', 'myEndSession');
    add_action('wp_login', 'myEndSession');
    
    function myStartSession() {
        if(!session_id()) {
            session_start();
        }
    }
    
    function myEndSession() {
        session_destroy ();
    }
    

    This destroys old session when user logs out then in again with different account.

    0 讨论(0)
  • 2020-12-09 04:28

    I've changed my original answer to the correct one from @rafi (see below).

    Write the following code in your functions.php file:

    function register_my_session()
    {
      if( !session_id() )
      {
        session_start();
      }
    }
    
    add_action('init', 'register_my_session');
    
    0 讨论(0)
  • 2020-12-09 04:34

    EDIT

    Wordpress sends header info before the header.php file is run. So starting the session in the header.php may still conflict with the header info that wordpress sends. Running it on init avoids that problem. (From jammypeach's comment)

    Write the following code in your functions.php file:

    function register_my_session()
    {
      if( !session_id() )
      {
        session_start();
      }
    }
    
    add_action('init', 'register_my_session');
    

    Now if you want to set data in session, do like this

    $_SESSION['username'] = 'rafi';
    
    0 讨论(0)
提交回复
热议问题