如何设置会话并检查是否在其他页面中设置了会话

时间:2014-04-05 19:22:53

标签: php session

如何在PHP中设置会话(对于登录表单),然后在名为view.php的页面上设置会话 - 如果会话尚未登录,则不显示页面,但如果是是,显示它? 登录部分正在运行,并告诉我是否已登录,以及用户名或密码等是否不正确,但是,我希望它在您登录时存储cookie /会话,然后带您查看.php - >但如果你没有登录并尝试访问view.php - 不允许你。

目前代码:

<?php
require 'db/connect.php';
// CONNECT TO MYSQLI
$db2 or die(mysqli_errno());

// FETCH DATA FROM FORM USING METHOD POST
// IF BUTTON NAME "LOGIN" IS SET
if (isset($_POST['login'])) {





// FETCH DATA FROM INPUT FIELD
$user = mysqli_real_escape_string($db2, $_POST['user']);
$pass = mysqli_real_escape_string($db2, $_POST['pass']);

  // CHECK ALL FIELD HAS BEEN FILLED UP
 if ($user && $pass != "") {

   // QUERY FROM DATABASE
  $query = mysqli_query($db2, "SELECT * FROM members WHERE username='".$user."'");
  $checkuser = mysqli_num_rows($query);


   // CHECK IF USERNAME EXIST ON DATABASE
  if($user != $checkuser) {

  }
else{
    echo 'Invalid Credentials';
}
   // FETCHING PASSWORD IN DATABASE WHERE USERNAME COINCIDES
 while  ($row = mysqli_fetch_array($query)) {

   $checkpass= $row['password'];


    // CHECK IF ENTERED PASSWORD MEETS THE USERNAME PASSWORD
   if ($pass == $checkpass) {




     // IF ALL OKAY SET SESSION
setcookie("user", $user, time()+7200);
    $_SESSION['user'] = $user;
    $_SESSION['start'] = time();
    $_SESSION['expire'] = $_SESSION['start'] + (60 * 60 * 60);
    session_start();
    $_SESSION['user'] = 1;
echo 'you are logged in';
    exit();

   } else {

     // SET VARIABLE THAT'LL SHOW IF USER PASSWORD IS INCORRECT
   echo "Invalid Credentials";

   }
  }
 } else {

  // SET VARIABLE IF ALL FIELD ARE NOT FILLED UP
 $error = "Please enter a username and password.";
 echo $error;
 }
}
?>


<title>*******</title>
<link rel="stylesheet" href="assets/css/bootstrap.css">
<link rel="stylesheet" href="assets/css/custom.css">
<div style="text-align: center;">

<form action="" method="post" id="loginForm">
<span class="input">Username: <input type="text" name="user" maxlength="16"></span>
<span class="input">Password: <input type="password" name="pass">
<input type="submit" name="login" value="Login"></input>

1 个答案:

答案 0 :(得分:1)

Yous可以编写一个函数来检查会话用户是否已设置,如果未设置,则重定向到登录页面。

function redirect(){
return !isset($_SESSION['user']);
}

在view.php文件中启动会话并包含以下条件。

<?php 
session_start(); 
//if session doesn't have a username it will redirect to login.php page
if(redirect()){
header("Location: login.php");
die();
}
?>