[英]How to change login details so they are stored in cookies so user remains logged in and not expire
我想創建一個用戶登錄的簡單登錄系統,然后它將保存登錄用戶的詳細信息並始終登錄,直到他們點擊退出鏈接。 現在我聽說用戶使用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)中,以便它知道哪個用戶已登錄。但目前我使用$ SESSION來執行此操作,其中包含少量時間:
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是否正確?
簡單(但錯誤)的答案是你用setcookie('blah', $value, time() + ages);
替換所有$_SESSION['blah'] = $value
setcookie('blah', $value, time() + ages);
但是您遇到的問題是您在會話中存儲用戶信息 - 如果您存儲在cookie中,則可以輕松更改該信息。
因此,您需要一種本地(在服務器上)存儲個人詳細信息的方式,以及一個用於調用這些詳細信息的參考編號 - 基本上您需要復制會話,但使用您自己的數據庫(或文件存儲)。
通常這是在數據庫中完成的:您創建一個“會話”數據庫,為每個用戶提供唯一的sessionID(難以猜測,而不是直接數字),然后將該會話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();
}
}
我建議的是延長會話到期時間。 通常會話在瀏覽器關閉時到期,您可以從ini設置更改此設置。 請參閱http://php.net/manual/en/session.configuration.php不一定是您正在尋找的,即永遠,但延長時間可能是一個合理的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.