php 如何在 Wordpress 中使用 session_start?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11797351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use session_start in Wordpress?
提问by Rob
I'm creating a bilingual site and have decided to use session_startto determine the language of the page using the following:
我正在创建一个双语网站,并决定使用以下内容session_start来确定页面的语言:
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:
问题在于它与 Wordpress 冲突,我得到以下信息:
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
警告:session_start() [function.session-start]:无法发送会话 cookie - 头已经发送(输出开始于 /home/neurosur/public_html/v2/wp-content/themes/default/header.php:8) /home/neurosur/public_html/v2/wp-content/themes/default/region.php 第 13 行
Is there a way to get around this?
有没有办法解决这个问题?
采纳答案by kpotehin
Move your code to the top of header.php file. And check if session already exists:
将您的代码移动到 header.php 文件的顶部。并检查会话是否已经存在:
if(session_id() == '')
session_start();
your code here...
回答by rafi
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)
Wordpress 在 header.php 文件运行之前发送标题信息。因此在 header.php 中启动会话可能仍然与 wordpress 发送的标题信息冲突。在 init 上运行它可以避免这个问题。(来自 jammypeach 的评论)
Write the following code in your functions.php file:
在您的functions.php 文件中写入以下代码:
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';
回答by j.c
I found an interesting article by Peter here. I'm using the following code in my functions.php:
我在这里找到了 Peter 的一篇有趣的文章。我在我的中使用以下代码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.
当用户注销然后使用不同的帐户再次登录时,这会破坏旧会话。

