Using session in WP without trouble with the API REST

I build a custom plugin that make me able to use SESSION to passe parameters from a page to others pages without GET parameters.

This works very well.

Basically i start my session like this :

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

}

And then set session variable like this in different part of the site

$_SESSION['key']  = value;

And finish like this

add_action('wp_logout', 'myEndSession');

function myEndSession() {
  session_destroy();
}

Problem : If i go on Tools Health Site, i have 2 errors :

  • An active PHP session was detected
  • API REST Error : cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received (http_request_failed)

If i comment my start session line i don't have the 2 errors more. But i need this session. How can i make it different ?

Topic session Wordpress

Category Web


The only way to make this go away is to not use PHP sessions and use cookies directly instead.

PHP sessions are fundamentally incompatible with a lot of page caching and CDN mechanisms e.g. cloudflare, Varnish, or full page caching plugins such as batcache or WP Supercache. PHP Sessions are also turned off and disabled on a lot of WP hosts e.g. WP Engine.

You cannot rely on PHP sessions in WordPress, especially if you want to write portable code or sell themes/plugins.

PHP Sessions also can't be used to bypass cookies as the session ID itself is stored in a cookie. There are also security consequences as the user can change this ID in the browser dev tools to retrieve the information of other users.

Instead use standard cookies instead. e.g. setcookie( 'key', 'value' );. This is what WordPress itself does, it's also how a lot of e-commerce sites implement carts ( think for a moment, how do sites that aren't built in PHP do it? PHP sessions are unnecessary ).

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.