Wordpress Plugin Sessions only work when logged in

2019-07-30 18:56发布

I am having trouble with a Wordpress plugin I am working on. PHP Sessions are not behaving consistently. I have read the following articles:

https://wordpress.stackexchange.com/questions/121144/session-in-wordpress-plugin-development

https://silvermapleweb.com/using-the-php-session-in-wordpress/

And many more that give the same advice about starting the session using the init hook.

I have implemented this in my plugin:

add_action('init', 'set_session', 1);

function set_session(){
    if(!session_id()){
        session_start();
    }
}

The sessions are still behaving oddly, so I have created a test to see if the sessions are being set.

$_SESSION['GuestID'] = 'test';

if(!session_id()){
    echo 'Session Not Started';
} else{
    if(isset($_SESSION['GuestID'])){
        echo 'Guest ID From Session: '.$_SESSION['GuestID'];
    } else{
        echo 'Guest ID not set in Session!';
    }
}

When I run this, the guest ID is returned 'Guest ID From Session: test', however if you reload try to access the session from another page, you get the 'Guest ID not set in Session!' message. To me this indicates the session has been started, but for some reason it is not storing my session data.

I can also see that there is no cookie being stored for the session id.

The weird part of all this, is that if I log in to the Wordpress admin, the PHP session id is stored in a cookie, and the sessions behave as expected!

What could be causing this? And how can I resolve the issue?

1条回答
仙女界的扛把子
2楼-- · 2019-07-30 19:21

After doing some further research, it appears that some Wordpress optimised hosting services have high levels of caching that delivers static content to the browser, without executing the PHP on each request. These caching services do not run when logged into the admin section of the wordpress site, leading to the inconsistent session performance. Sessions didn't work when accessing the cached pages, and worked when not cached.

My hosting provider uses Varnish, and disabling Varnish for the site in question has resolved the issue.

查看更多
登录 后发表回答