0

現時点では、これが私のログインおよびログオフ システムのしくみです。

ユーザーがログインすると、member.php と呼ばれるスクリプトの $_SESSION に詳細が保存されます。

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

      $userid = $_SESSION['teacherid'];

  }

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

      $username = $_SESSION['teacherusername'];

  }

次に、すべてのスクリプトに、セッションライフが 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>";

?>

ファイル:logout.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 に答える