duanhui7329 2014-02-24 19:47
浏览 20
已采纳

使用PHP会话变量来保持用户登录网站

I want to assign a value to a session variable when a user logs into a website. I read that I must explicitly start a session at the top of my pages in order to do this. So I inserted:

if (!isset($_SESSION)){
    session_start();
    echo "started";
}

The first thing I notice is that "started" is displayed every time I reload my page. Is that expected behavior? I would assume the second time I load the page, the session should already be there, therefore "started" would not display.

Further down in my page, I have:

$_SESSION['id']=2;
echo "<p>Your session ID is: " . $_SESSION['id'] . "</p>";

That correctly displays the ID in the "echo" statement. So even after assigning a value to a session variable, when I reload the page, it puts "started" at the top.

Am I doing something wrong? Thank you!

  • 写回答

2条回答 默认 最新

  • dpfwhb7470 2014-02-24 19:50
    关注

    That is expected behaviour, you need to call session_start() before any output is sent to the browser every time the page is loaded, which is why your echo is happening every time. You if statement in this case is a little unnecessary and you should just simply call it without the if.

    session_start();
    

    For example, a $_SESSION variable will never be accessible unless you call session_start(), despite the fact that it will exist in the browser's session. Calling session_start() simply allows you to access that superglobal array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改