Wordpress 插件会话仅在登录时有效 [英] Wordpress Plugin Sessions only work when logged in

查看:42
本文介绍了Wordpress 插件会话仅在登录时有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Wordpress 插件时遇到问题.PHP Session 的行为不一致.我已阅读以下文章:

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/

还有更多关于使用 init 钩子启动会话的相同建议.

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!';
    }
}

当我运行此程序时,访客 ID 会返回来自会话的访客 ID:测试",但是如果您重新加载尝试从另一个页面访问会话,则会得到会话中未设置访客 ID!"信息.对我来说,这表明会话已经开始,但由于某种原因它没有存储我的会话数据.

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.

我还可以看到没有为会话 ID 存储 cookie.

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

这一切的奇怪之处在于,如果我登录到 Wordpress 管理员,PHP 会话 ID 存储在 cookie 中,并且会话的行为符合预期!

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?

推荐答案

经过进一步研究后,似乎一些 Wordpress 优化的托管服务具有高级缓存,可以向浏览器提供静态内容,而无需在每个服务器上执行 PHP要求.这些缓存服务在登录 wordpress 站点的管理部分时不会运行,从而导致会话性能不一致.访问缓存页面时会话不工作,未缓存时会话工作.

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.

我的托管服务提供商使用 Varnish,为相关网站禁用 Varnish 已解决问题.

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

这篇关于Wordpress 插件会话仅在登录时有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆