页面重新加载后会话被破坏

时间:2018-03-09 16:09:11

标签: php ajax session

我有一个登录表单,它触发ajax到设置会话的php页面。如果ajax的回归成功'它重新加载页面。会话变量第一次出现在那里。但如果按F5重新加载同一页面,会话就会消失。

登录表单页

<?php 
  session_start();
  include 'connect.php';
  if(isset($_SESSION['id'])) {
    $id = intval($_SESSION['id']);
    $result = $conn->query("SELECT * FROM users WHERE id = $id LIMIT 1");
    $user   = $result->fetch_assoc();
    $ids    = explode(',', $user['ids']);
    $tiers  = explode(',', $user['tiers']);
    $ranks  = explode(',', $user['ranks']);
    $levels = explode(',', $user['levels']);
    $sigs   = explode(',', $user['sigs']);
  }
?>
<form>
  <div class="login">
    <div><span>Username / E-mail:</span><input type="text" name="login"/></div>
    <div><span>Password:</span><input type="password" name="password"/></div>
    <div><button type="button" class="login">Login</button><button type="button" class="cancel">Cancel</button></div>
  </div>
</form>

的javascript

document.querySelector('button.login').addEventListener('click', function() {
  var form = document.forms[0];
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if(this.readyState == 4) {
      if(this.responseText == 'success') location.reload();
      else alert(this.responseText);
    }
  }
  xhttp.open('POST', 'ajax.php', true);
  xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  request = 'login=' + form.login.value + '&password=' + form.password.value + '&action=login';
  xhttp.send(request);
});

ajax.php

<?php
  session_start();
  include 'connect.php';
  extract($_POST);

  if($action == 'login') {
    $stmt = $conn->prepare('SELECT id FROM users WHERE (name = ? OR email = ?) AND password = ? LIMIT 1');
    $stmt->bind_param('sss', $login, $login, $password);
    $stmt->bind_result($id);
    $stmt->execute();
    $stmt->store_result();
    if($stmt->num_rows < 1) die('Wrong username/email or password');
    $user = $stmt->fetch();
    $_SESSION['id'] = $id;
    echo 'success';

  }

0 个答案:

没有答案