How to use session_start in Wordpress?

Viewed 63727

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();    
if(!isset($_SESSION['language'])){
    $_SESSION['language'] = 'English'; //default language
}

The problem with this is that it clashes with Wordpress and I get the following:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/neurosur/public_html/v2/wp-content/themes/default/header.php:8) in /home/neurosur/public_html/v2/wp-content/themes/default/region.php on line 13

Is there a way to get around this?

6 Answers

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.

for PHP version 7.4

function register_my_session() {

    if (session_status() === PHP_SESSION_NONE && session_status() !== PHP_SESSION_ACTIVE) {
        @session_start();
    } 
} 
add_action('init', 'register_my_session');
add_action('init', 'customSessionStart', 1);
add_action('wp_logout', 'customSessionDestroy');
add_action('wp_login', 'customSessionDestroy');
function customSessionStart()
{
    if (!session_id()) {
        session_start();
    }
}
function customSessionDestroy()
{
    session_destroy();
}

When you use this code, you may get the critical issue in the WP Site Health Status. The error says that;

A PHP session was created by a session_start() function call. This interferes with REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.

To suppress this error, you may make this revision when you want to start a session in the WP;

session_start([
    'read_and_close' => true,
]);
Related