dousou1967 2015-05-11 08:57
浏览 46
已采纳

会话不工作PHP

The session is not getting created and keep getting redirected to login.php. Really don't understand why! I really need help :(

Here is my Session class:

class Session {

    private $logged_in=false;
    public $user_id;

    function __construct() {
        session_start();
        $this->check_login();
    if($this->logged_in) {
      // actions to take right away if user is logged in
    } else {
      // actions to take right away if user is not logged in
    }
    }

  public function is_logged_in() {
    return $this->logged_in;
  }

    public function login($user) {
    if($user){
      $this->user_id = $_SESSION['user_id'] = $user->id;
      $this->logged_in = true;
    }
  }

  public function logout() {
    unset($_SESSION['user_id']);
    unset($this->user_id);
    $this->logged_in = false;
  }

    private function check_login() {
    if(isset($_SESSION['user_id'])) {
      $this->user_id = $_SESSION['user_id'];
      $this->logged_in = true;
    } else {
      unset($this->user_id);
      $this->logged_in = false;
    }
  }

}

$session = new Session();

?>

Here is a part of my Login page:

if (isset($_POST['submit'])) { // Form has been submitted.

  $user_name = trim($_POST['user_name']);
  $password = trim($_POST['password']);

  // Check database to see if username/password exist.
    $found_user = User::authenticate($user_name, $password);

  if ($found_user) {
    $session->login($found_user);
    redirect_to("index.php");
  } else {
    // username/password combo was not found in the database
    $message = "Username/password combination incorrect.";
  }

} else { // Form has not been submitted.
  $user_name = "";
  $password = "";
}

And here is a part of the index.php:

if (!$session->is_logged_in()) { redirect_to("login.php");

What I have tried:

I tried putting a session_start(); at the start no luck. Looked for errors in all the code used in these pages.

  • 写回答

3条回答 默认 最新

  • drv54591 2015-05-11 09:08
    关注

    Call the session_start(); before the if statement in the login page.

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

报告相同问题?

悬赏问题

  • ¥20 易康econgnition精度验证
  • ¥15 线程问题判断多次进入
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致