PHP不会将会话设置为TRUE

时间:2015-05-18 15:10:36

标签: php session

我正在尝试创建一个登录系统但它似乎没有设置" Session = true"。请帮助我长期坚持这一点。

会话开始 检查了我的所有代码 没有PHP错误 并且没有数据库错误

登录页面:

if($session->is_logged_in()) {
  redirect_to("index.php");
}


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 = "";
}

会话班:

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) {
    // database should find user based on username/password
    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();

索引页:

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

授权方法:

public static function authenticate($user_name="", $password="") {
    global $database;
    $user_name = $database->escape_value($user_name);
    $password = $database->escape_value($password);

     $sql="SELECT * FROM users WHERE user_name='{$user_name}' AND password ='{$password}' LIMIT 1";
    $result_array = self::find_by_sql($sql);
        return !empty($result_array) ? array_shift($result_array) : false;
    }

2 个答案:

答案 0 :(得分:1)

将您的is_logged_in()函数更改为:

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

否则,is_logged_in()将始终在每个新请求上返回false(例如在页面之间重定向)。通过首先调用check_login(),它将使用值设置logged_in变量(true或false,取决于是否设置了$ _SESSION ['user_id']。

编辑:

对不起,我忽略了你已经调用$ this-> check_login();

的构造函数中的行

另一件事是authenticate函数返回一个Array而不是一个对象。因此,请更改以下内容:

$this->user_id = $_SESSION['user_id'] = $user->id;

$this->user_id = $_SESSION['user_id'] = $user['id'];

答案 1 :(得分:0)

最后我找到了解决方案。

猜猜是什么?这不是我的代码故障,但它是我的服务器(WAMP 2)故障。因此,我卸载了WAMP 2并更新到较新版本的WAMP 2.5。解决了我的问题,不再需要重定向到登录页面了!