1

ユーザーがログインする単純なログイン システムを作成すると、ログインしたユーザーの詳細が保存され、ログアウト リンクをクリックするまで常にログインされます。これを行うには、Cookie を使用する方がよいと聞きました。以下はログインページです。

teacherlogin.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');
include('member.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

}

?>

上記のコードでは、ユーザーは関連するテキスト入力にユーザー名とパスワードを入力します。ログインの詳細を送信すると、データベースをチェックインして、ログインの詳細がデータベースで一致するかどうかを確認します。

今私がしたいのは、ユーザーのユーザー名と id の詳細を php スクリプト (member.php) に保存して、どのユーザーがログインしているかを知ることです。時間の:

member.php ページ:

<?php

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

      $userid = $_SESSION['teacherid'];

  }

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

      $username = $_SESSION['teacherusername'];

  }

        ?>

上記のコードを変更して Cookie を使用し、メンバー ページのユーザーの詳細が無期限 (もちろんログアウトするまで) 保持されるようにするにはどうすればよいですか。

アップデート:

Teacherこれがデータベースのテーブルです。

TeacherId (auto PK) TeacherForename  TeacherSurname TeacherUsername, TeacherPassword
1                   John             Parks          j.parks          b018460fba79b
2                   Mary             Little         u0876555         a33rfe3tn12e3
3                   Jim              Owen           owensjimmy       fkof04r3fk422

つまり、最初に列 SessionId を上記のテーブルに追加し、各ユーザーの複雑な ID に格納すると言っています34dekfm45345

それでは、正しいSessionIdを見つけてSessionIdを削除する方法に関するコードを確認できるようにするために、あなたの助けが本当に必要です.

更新 2:

したがって、私が正しく理解していれば、php スクリプトは次のようになります。

teacherlogin.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');
    include('member.php');
    include('sessionuser.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

    }

    ?>

ユーザーが現在ログインしているかどうかを確認するコードを変更していませんif ((isset($username)) && (isset($userid))){。関連するものに変更しますか? 上記の `include(sessionuser.php) コードを含めました

member.php スクリプト:

<?php

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

          $userid = $_SESSION['teacherid'];

      }

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

          $username = $_SESSION['teacherusername'];

      }

            ?>

上記の member.php スクリプトはまだ必要ですか?

sessionuser.php スクリプト:

$sessionUserID = false;

if (isset($_COOKIE['sessionUserID']) && preg_match('/^[a-z9-0]{32}$/i) {
    $sessionUserID = $_COOKIE['sessionUserID'];

    // Get the session details from the database
    $sql = 'SELECT s.*, t.* FROM SessionUser s LEFT JOIN Teacher t ON s.TeacherId=t.TeacherId WHERE s.SessionUserId=:SessionUserId';
    $aParams = array(':SessionUserId' => $sessionUserID)
    $sessionRow = $stmnt->fetch();
    if ($sessionRow) {
        // User is logged in, and you have details in $sessionRow
        // At this point, you can also validate other info such as the UserAgent, IP etc. All forgable, but can help add a littel security.
    } else {
        // Passed an invalid / expired session ID
        $sessionUserID = false;
    }
}

// If you don't have a session, create one
if (!$sessionUserID) {
    // Create a session user ID - make it non sequential
    // You should put this in a loop and check $sessionID is unique. Insert will fail is not unique
    $sessionUserID = md5(time() . uniqid());
    $sql = 'INSERT INTO SessionUser(SessionUserId, TeacherId)
              VALUES(:SessionUserId, 0)';
    $aParams = array(':SessionUserId' => $sessionUserID)
    $smnt->execute();

    // Default session details
    $sessionRow = array('TeacherId'=>0);

    // Now the cookie part
    setcookie('sessionUserID', $sessionUserID, time() + howLongYouWant, '/');
}

// Not check for user logging in.
if (UserLogsIn) {
    if ($sessionRow['teacher_id'] > 0) {
         // Already logged in!?
    } else {

        $sql = 'UPDATE SessionUser SET Teacher_id=:TeacherId WHERE SessionUserId=:SessionUserId';
        $aParams = array(':TeacherId'=>$TeacherId, ':SessionUserId' => $sessionUserID);
        $smnt->execute();

        // After a form post, always redirect to the same page or another page - stops the "do you want to resent this data" message on back button
        // DO NOT echo anything before this point.
        header('location: this page');
        exit();
    }
} elseif (UserLogsOut) {
    if ($sessionRow['TeacherId'] == 0) {
         // Not Logged In!?
    } else {

        $sql = 'UPDATE SessionUser SET TeacherId=0 WHERE SessionUserd=:SessionUserid';
        $aParams = array(':session_id' => $sessionID);
        $smnt->execute();

        // After a form post, always redirect to the same page or another page - stops the "do you want to resent this data" message on back button
        // DO NOT echo anything before this point.
        header('location: this page');
        exit();
    }
}

sessionuser.php スクリプト コードに上記のコードがすべて含まれているというのは正しいですか? 以下のデータベーステーブルと一致するようにコードを変更しました。

SessionUser テーブル:

SessionUserId (CHAR32) PK
TeacherId (INT) //matches TeacherId field in teacher table

更新 2 は正しいですか?

4

2 に答える 2

3

単純な (しかし間違った) 答えは、すべて$_SESSION['blah'] = $valueを次のように置き換えることです。setcookie('blah', $value, time() + ages);

しかし、問題は、セッションにユーザー情報を保存していることです。その情報を Cookie に保存すると、簡単に変更できます。

そのため、個人情報を保存するローカル (サーバー上) の方法と、それらの詳細を思い出すための参照番号が必要です。基本的には、セッションを複製する必要がありますが、独自のデータベース (またはファイル ストア) を使用します。

通常、これはデータベースで行われます。「セッション」データベースを作成し、各ユーザーに一意のセッション ID (単純な数字ではなく、推測が難しい) を与えてから、そのセッション ID を Cookie に保存し、個人の詳細をデータベースに保存します。 . 次に、セッション Cookie を取得し、データベースから詳細を呼び出します。彼らがログアウトしたら、データベースなどのエントリを削除します。サーバーが再起動してセッションが失われた場合、セッション データはデータベースにあるため安全です。ユーザーは、不要になるまで常にログインしています。

つまり、単純な答えと、より複雑な本当の答えがあります。


編集:

リクエストに応じて、すぐにプロセスを実行できます。私はエラーチェックと DB 呼び出しのためのすべてのジャズを逃しました。これで始められるはずです。

// Create a DB with the following structure
session_id CHAR(32) PRIMARY KEY
teacher_id INT(mathc your teachers table)

// Check for cookie, validate it's an expected format
$sessionID = false;

if (isset($_COOKIE['sessionID']) && preg_match('/^[a-z9-0]{32}$/i) {
    $sessionID = $_COOKIE['sessionID'];

    // Get the session details from the database
    $sql = 'SELECT s.*, t.* FROM sessions s LEFT JOIN teachers t ON s.teacher_id=t.teacher_id WHERE s.session_id=:session_id';
    $aParams = array(':session_id' => $sessionID)
    $sessionRow = $stmnt->fetch();
    if ($sessionRow) {
        // User is logged in, and you have details in $sessionRow
        // At this point, you can also validate other info such as the UserAgent, IP etc. All forgable, but can help add a littel security.
    } else {
        // Passed an invalid / expired session ID
        $sessionID = false;
    }
}

// If you don't have a session, create one
if (!$sessionID) {
    // Create a session ID - make it non sequential
    // You should put this in a loop and check $sessionID is unique. Insert will fail is not unique
    $sessionID = md5(time() . uniqid());
    $sql = 'INSERT INTO sessions(session_id, teacher_id)
              VALUES(:session_id, 0)';
    $aParams = array(':session_id' => $sessionID)
    $smnt->execute();

    // Default session details
    $sessionRow = array('teacher_id'=>0);

    // Now the cookie part
    setcookie('sessionID', $sessionID, time() + howLongYouWant, '/');
}

// Not check for user logging in.
if (UserLogsIn) {
    if ($sessionRow['teacher_id'] > 0) {
         // Already logged in!?
    } else {

        $sql = 'UPDATE sessions SET teacher_id=:teacher_id WHERE session_id=:session_id';
        $aParams = array(':teacher_id'=>$teacher_id, ':session_id' => $sessionID);
        $smnt->execute();

        // After a form post, always redirect to the same page or another page - stops the "do you want to resent this data" message on back button
        // DO NOT echo anything before this point.
        header('location: this page');
        exit();
    }
} elseif (UserLogsOut) {
    if ($sessionRow['teacher_id'] == 0) {
         // Not Logged In!?
    } else {

        $sql = 'UPDATE sessions SET teacher_id=0 WHERE session_id=:session_id';
        $aParams = array(':session_id' => $sessionID);
        $smnt->execute();

        // After a form post, always redirect to the same page or another page - stops the "do you want to resent this data" message on back button
        // DO NOT echo anything before this point.
        header('location: this page');
        exit();
    }
}
于 2012-11-15T02:17:37.430 に答える
0

私が提案するのは、セッションの有効期限を延長することです。通常、ブラウザを閉じるとセッションが期限切れになりますが、これはini設定から変更できます。http://php.net/manual/en/session.configuration.phpを参照してください 。まさにあなたが探しているもの、つまり永遠ではありませんが、時間を延長することは合理的な解決策かもしれません。

于 2012-11-15T02:51:14.550 に答える