0

目前这是我的登录和注销系统的工作方式:

当用户登录时,它会将他们的详细信息存储在名为 member.php 的脚本中的 $_SESSION 中:

if (isset($_SESSION['teacherid'])) {

      $userid = $_SESSION['teacherid'];

  }

if (isset($_SESSION['teacherusername'])) {

      $username = $_SESSION['teacherusername'];

  }

然后在每个脚本中,它包含下面的代码,其中 sessionlife 持续 12 小时:

 <?php

    ini_set('session.gc_maxlifetime',12*60*60);
    ini_set('session.gc_divisor', '1');
    ini_set('session.gc_probability', '1');
    ini_set('session.cookie_lifetime', '0');
    require_once 'init.php'; 

    session_start();

include(member.php)

    ?>

init.php 如下:

 <?php
 session_save_path('Session'); 
 ?>

现在在 12 小时后用户下次刷新页面时,由于会话将被销毁,它会进入注销页面:

if ((isset($username)) && (isset($userid))){
    session_destroy();
    echo "You have been Logged Out | <a href='./home.php'>Home</a>";
}

else {

    echo "You are Not Logged In";

}

显然,如果用户单击注销页面,那么它会导航到上面的脚本。

但是我发现了一种更好的方法来保持用户的登录状态,并且让他们在他们自己注销之前不注销是使用下面的代码:

if (session_exists) continue();
else if (!session_exists AND cookie_exists AND validate_cookie()) {
    login_user_via_cookie();
    continue();
else show_login_page();

我的问题是,首先我将这段代码放在哪里,我是否用 session_maxlife 和我设置的所有 ini_set 代码替换它?我是否需要替换任何代码,是否需要更改上面找到的代码以使其在我的脚本中工作?(我的注销页面位于名为 Text4.php 的脚本中)

谢谢

更新:

teacherlogin.php 页面:

<?php
/*
file: login.php
authorized (logged in) users must be redirected to a secure page (member.php) or (secure.php)
unauthorized (guests) users have to see the login form
*/

#include the class file and start it.
require_once('session.class.php');
$session = new Session();

#check user's access
if($session->get("auth")) header("location:member.php");

ini_set('display_errors',1); 
error_reporting(E_ALL);


session_start();

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php

// connect to the database
include('member.php');
include('connect.php');

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}

// required variables (make them explciit no need for foreach loop)
$teacherusername = (isset($_POST['teacherusername'])) ? $_POST['teacherusername'] : '';
$teacherpassword = (isset($_POST['teacherpassword'])) ? $_POST['teacherpassword'] : '';
$loggedIn = false;
$active = true;

if ((isset($username)) && (isset($userid))){
echo "You are already Logged In: <b>{$_SESSION['teacherforename']} {$_SESSION['teachersurname']}</b> | <a href='./menu.php'>Go to Menu</a> | <a href='./teacherlogout.php'>Logout</a>";
}
else{

if (isset($_POST['submit'])) {

$teacherpassword = md5(md5("g3f".$teacherpassword."rt4"));  

// don't use $mysqli->prepare here
$query = "SELECT TeacherId, TeacherForename, TeacherSurname, TeacherUsername, TeacherPassword, Active FROM Teacher WHERE TeacherUsername = ? AND TeacherPassword = ? LIMIT 1";
// prepare query
$stmt=$mysqli->prepare($query);
// You only need to call bind_param once
$stmt->bind_param("ss",$teacherusername,$teacherpassword);
// execute query
$stmt->execute(); 
// get result and assign variables (prefix with db)
$stmt->bind_result($dbTeacherId, $dbTeacherForename,$dbTeacherSurname,$dbTeacherUsername,$dbTeacherPassword, $dbActive);

while($stmt->fetch()) {
if ($teacherusername == $dbTeacherUsername && $teacherpassword == $dbTeacherPassword) {
if ($dbActive == 0) {
$loggedIn = false;
$active = false;
echo "You Must Activate Your Account from Email to Login";
}else {
$loggedIn = true;
$active = true;
$_SESSION['teacherid'] = $dbTeacherId;
$_SESSION['teacherusername'] = $dbTeacherUsername;
}
}
}

if ($loggedIn == true){
$_SESSION['teacherforename'] = $dbTeacherForename;
$_SESSION['teachersurname'] = $dbTeacherSurname;
header( 'Location: menu.php' ) ;
die();
}

if (!$loggedIn && $active && isset($_POST)) {
echo "<span style='color: red'>The Username or Password that you Entered is not Valid. Try Entering it Again</span>";
}

/* close statement */
$stmt->close();

/* close connection */
$mysqli->close();
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Teacher Login</title>
<link rel="stylesheet" type="text/css" href="TeacherLoginStyle.css">
</head>
<body>

<?php
include('noscript.php');
?>

<h1>TEACHER LOGIN</h1>

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" id="teachLoginForm">        
<p>Username</p><p><input type="text" name="teacherusername" /></p>      <!-- Enter Teacher Username-->
<p>Password</p><p><input type="password" name="teacherpassword" /></p>  <!-- Enter Teacher Password--> 
<p><input id="loginSubmit" type="submit" value="Login" name="submit" /></p>
</form>

<a href="./forgotpass.php">Forgot Password</a>

</body>

<?php

}

?>
</html>

teacherlogout.php 页面:

<?php

require_once('session.class.php');
$session = new Session();

ini_set('display_errors',1); 
error_reporting(E_ALL);


session_start();

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Menu</title>

<link rel="stylesheet" type="text/css" href="menu.css">

</head>

<?php

include('member.php');
include('noscript.php');

?>

<body>

<?php

if($session->get("auth")){
session_destroy();
echo "You have been Logged Out | <a href='./home.php'>Home</a>";
}

else {

echo "You are Not Logged In";

}

?>

</body>
</html>

member.php 页面:

<?php

/*
file: secure.php, profile.php, member.php
authorized (logged in) users => log them out and show goodbye msg or send them to login.php
unauthorized (guests) users => redirect them to login.php
*/
require_once('session.class.php');
$session = new Session();

#if user is not logged in, he will be sent to the login.php page
#note the (!) sign before the $session, it means if the $session->get("auth") == false
if(!$session->get("auth")) header("location:teacherlogin.php");

#if user is not logged in, he will be sent to the login.php page
#note the (!) sign before the $session, it means if the $session->get("auth") == false
if(!$session->get("auth")) header("location:teacherlogin.php");


//need to the code below in order to store details of teacher that is logged in (needed for queries in other pages)

if (isset($_SESSION['teacherforename'])) {

$_SESSION['teacherforename'] = $_SESSION['teacherforename'];

}

if (isset($_SESSION['teachersurname'])) {

$_SESSION['teachersurname'] = $_SESSION['teachersurname'];

}

if (isset($_SESSION['teacherid'])) {

$userid = $_SESSION['teacherid'];

}

if (isset($_SESSION['teacherusername'])) {

$username = $_SESSION['teacherusername'];

}

?>
4

1 回答 1

1

如果需要,这是一个可以使用和编辑的类:

文件session.class.php

<?php
/*
Simple PHP Session Class:
    a simple class to help managing the Session function in
    php for beginners and it introduces them to OOP where
    they can modify it and add new features and extend its
    functionality (session in database, track users actions,etc)
*/
#Session settings.

#Session cookie lifetime at the user browser. (seconds)
ini_set('session.cookie_lifetime', '0');

#Read the functions reference below before you change these values.
ini_set('session.gc_maxlifetime',7200);# 2 hours.
ini_set('session.gc_probability', '1'); #default PHP value.
ini_set('session.gc_divisor', '100'); #default PHP value.

/*====================================================================

ini_set('session.cookie_lifetime', '0');

    User cookie life time in seconds.
    0 means the cookie wont expire until the user closes the broswer


ini_set('session.gc_maxlifetime',7200); #default: 1440 (24 mins).

    Session Garbage Collection cleaner (GC). 

    7200(seconds) equals to (2 hours): The GC will try to
    clean session data in the server for (users who logged
    out, closed the browser AND users who are inactive for
    more than that time) however the clean function does
    not run directly, read the next block for more explaination.

    PHP manual:
        session.gc_maxlifetime specifies the number of
        seconds after which data will be seen as 'garbage'
        and potentially cleaned up. Garbage collection may
        occur during session start
        (depending on session.gc_probability and session.gc_divisor).


ini_set('session.gc_probability', '1'); #default PHP value (1).
ini_set('session.gc_divisor', '100'); #default PHP value (100).

    Garbage Collection (GC) Settings:
    PHP manual:
        session.gc_divisor coupled with
        session.gc_probability defines the probability
        that the gc (garbage collection) process is started
        on every session initialization. The probability is
        calculated by using gc_probability/gc_divisor
        e.g. 1/100 means there is a 1% chance that the GC
        process starts on each request.
        session.gc_divisor defaults to 100.  
====================================================================*/

/*
    HOW TO USE:
    - include the session file in all your files and call the session object
    require_once('session.class.php');
    $session = new Session();


    GET SESSION ID:
    - $session->sid;
      @return type (string)
      @example:
      echo $session->sid;

    GENEREATE NEW SESSION ID:
    - $session->re();
      @return type (string)
      #note: returns the value of the new session id.
      @example:
      $sid = $session->sid;
      $new_sid = $session->re();
      echo "My Session ID is: {$sid} but I got a new one now: {$new_sid};

    ASSIGN NEW SESSION VALUE:
    - $session->set($key,$value);
      @return type (void)
      @examples:
        $session->set("name","foo bar");
        $session->set("age",24);
        $session->set("auth",TRUE);

    GET SESSION VALUE:
    - $session->get($key);
      @return type (boolean, int, string, array).
      #note: returns FALSE if the value is not set
      @examples:
      echo $session->get("name");
      if($session->get("auth")) echo "hello authorized user!";

      if(($age = $session->get("age")) > 21)
      echo "your age is {$age}, you can drive!";

    DELETE SESSION VALUE:
    - $session->delete($key);
      @return type (void);
      @example
      $session->delete("age");

    DESTROY SESSION
    - $session->destroy();
      @return type (void);
*/
/*==================================================================*/
class Session{
    public $sid;
    public function __construct() {
        @session_start();
        $this->sid = session_id();
    }
    public function re(){
        @session_regenerate_id();
        $this->sid = session_id();
        return $this->sid;
    }
    public function set($key, $val) {
        $_SESSION[$key] = $val;
        return true;
    }

    public function get($key) {
        if ( isset($_SESSION[$key]) ) {
            return $_SESSION[$key];
        }

        return false;
    }

    public function delete($key) {
        unset($_SESSION[$key]);
    }

    public function destroy() {
        $_SESSION = array();
        session_destroy();
    }
}            
?>

文件:member.php

<?php
    ini_set('display_errors',1); 
    error_reporting(E_ALL);

    /*
    file: secure.php, profile.php, member.php
    authorized (logged in) users => log them out and show goodbye msg or send them to login.php
    unauthorized (guests) users => redirect them to login.php
    */
    require_once('session.class.php');
    $session = new Session();

    #if user is not logged in, he will be sent to the login.php page
    #note the (!) sign before the $session, it means if the $session->get("auth") == false
    if(!$session->get("auth")) header("location:teacherlogin.php");

    echo "hello, you are logged in";
    echo "<br />";
    echo "username: ".$session->get("teacherusername");
    echo "<br />";
    echo "teacherid: ".$session->get("teacherid");
    echo "<br />";
    echo "active status: ".$session->get("active") ? "Active" : "Not Active";
    echo "<br />";
    echo "<a href='logout.php'>Log out</a>";

?>

文件:注销.php

<?php
ini_set('display_errors',1); 
error_reporting(E_ALL);

require_once('session.class.php');
$session = new Session();

if($session->get("auth")){
    session_destroy();
    $msg = "You have been Logged Out | <a href='./home.php'>Home</a>";
}else{
    $msg = "You were not logged in, so you cant logout";
}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Menu</title>

<link rel="stylesheet" type="text/css" href="menu.css">

</head>

<?php
include('noscript.php');
?>

<body>
    <?= $msg ? $msg : '' ?>
</body>
</html>

文件:login.php

<?php
/*
file: login.php
authorized (logged in) users must be redirected to a secure page (member.php) or (secure.php)
unauthorized (guests) users have to see the login form
*/

#include the class file and start it.
require_once('session.class.php');
$session = new Session();

#check user's access
if($session->get("auth"))header("location:member.php");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php

// connect to the database
@include('connect.php');
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
}

// required variables (make them explciit no need for foreach loop)
if (isset($_POST['submit'])) {
    $teacherusername = (isset($_POST['teacherusername'])) ? $_POST['teacherusername'] : '';
    $teacherpassword = md5(md5("g3f".$_POST['teacherpassword']."rt4"));  

    // don't use $mysqli->prepare here
    $query = "SELECT TeacherId, TeacherForename, TeacherSurname, TeacherUsername, TeacherPassword, Active FROM Teacher WHERE TeacherUsername = ? AND TeacherPassword = ? LIMIT 1";
    // prepare query
    $stmt=$mysqli->prepare($query);
    // You only need to call bind_param once
    $stmt->bind_param("ss",$teacherusername,$teacherpassword);
    // execute query
    $stmt->execute(); 
    // get result and assign variables (prefix with db)
    $stmt->bind_result($dbTeacherId, $dbTeacherForename,$dbTeacherSurname,$dbTeacherUsername,$dbTeacherPassword, $dbActive);

    while($stmt->fetch()) {
        if ($teacherusername == $dbTeacherUsername && $teacherpassword == $dbTeacherPassword) {
            if ($dbActive == 0) {
                $error = "You Must Activate Your Account from Email to Login";
            }else{
                $session->set('auth',TRUE);
                $session->set('active',TRUE);
                $session->set('teacherid',$dbTeacherId);
                $session->set('teacherusername',$dbTeacherUsername);
                header('Location: member.php') ;
            }
        }else{
            //password and username dont match
                $error = "The Username or Password that you Entered is not Valid. Try Entering it Again";
        }
    }

    /* close statement */
    $stmt->close();

    /* close connection */
    $mysqli->close();
}
?>
于 2012-11-12T04:00:48.570 回答