PHP Autologin函数登录脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1382303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Autologin function to login script
提问by zombat
How would I implent an autologin feature to this script?
我将如何为此脚本实现自动登录功能?
session_start();
$result = mysql_query("SELECT id FROM users
WHERE username = '{$_POST['username']}'
AND password = '{$_POST['password']}'");
if (isset($_POST['savelogin'])) {
setcookie("SaveLogin", $_POST['username'], time()+3600);
setcookie("SaveLogin", $_POST['password'], time()+3600);
}
if (mysql_num_rows($result) == 0) {
exit('wrong username/password');
} else {
$_SESSION['id'] = mysql_result($result, 0, 'id');
header("Location: ./");
}
<form method="post">
Username: <input type="text" name="username" size="22" /><br>
Password: <input type="password" name="password" size="22" /><br>
<br>
Autologin? <input type="checkbox" name="savelogin" />
<input type="submit" value="Login" />
</form>
Thats how far i have gotten. Saving the username and password. But how should I do so it autologins?
这就是我得到的程度。保存用户名和密码。但是我应该怎么做才能自动登录?
回答by Dooltaz
First, you don't want to save the username and password to the cookie. That's a bad idea.
首先,您不想将用户名和密码保存到 cookie。这是个坏主意。
A simple method of thinking of this would be:
一个简单的思考方法是:
1) Create a new field in the users table that stores an MD5 hash. You can call it session_key.
2) When you submit the page, the script should do the following.
1) 在用户表中创建一个新字段,用于存储 MD5 哈希值。您可以将其称为 session_key。
2)当你提交页面时,脚本应该做以下事情。
- Validate the username and password
- If it is a good username and password pair, check for the saveLogin variable
- If the saveLogin variable is set, generate an md5 and store that in the database. Also store that md5 in a cookie. Be sure the database table has a cookie-expires field as well.
- Build the session data that you need.
- Redirect to ./
- 验证用户名和密码
- 如果是一个好的用户名和密码对,检查 saveLogin 变量
- 如果设置了 saveLogin 变量,则生成一个 md5 并将其存储在数据库中。还将该 md5 存储在 cookie 中。确保数据库表也有一个 cookie-expires 字段。
- 构建您需要的会话数据。
- 重定向到 ./
3) On your ./ page, do the following:
3) 在您的 ./ 页面上,执行以下操作:
- Check to see if the session still exists. If so, then render the page.
- If the session does not exist, check for the cookie.
- If the cookie exists, look up that session id in the database and be sure it hasn't expired. then build the session and render the page.
- 检查会话是否仍然存在。如果是,则呈现页面。
- 如果会话不存在,请检查 cookie。
- 如果 cookie 存在,请在数据库中查找该会话 ID 并确保它没有过期。然后构建会话并呈现页面。
This should make your app a bit more secure. It may not be the best way of coding, but the concepts should give you an idea of how to make a fairly secure login page.
这应该会使您的应用更加安全。这可能不是最好的编码方式,但这些概念应该让您了解如何制作一个相当安全的登录页面。
回答by zombat
That is a very insecure method of having an auto-login. You should never store the password anywhere in plaintext.
这是一种非常不安全的自动登录方法。您永远不应该将密码以明文形式存储在任何地方。
A better strategy is as follows:
更好的策略如下:
- Present the normal login form, with a checkbox for "auto login".
- If the auto login box is checked, then you verify their username and password normally. If this is successful, you can then set a special cookie for auto-logins.
- Give the special cookie a name like 'autologin', and a value that contains their username, and a salted md5 hash of their user data. Something like "user=username&hash=123456xyz.etc".
- When you see the user next time and want to auto-log-them-in, you check for this special cookie and verify its contents. Split off the username and hash, then fetch the account out of the database based on the username and re-do the md5 to compare to the cookie hash data. If it's valid, you can log them in (ie. start a new session).
- 显示普通登录表单,并带有“自动登录”复选框。
- 如果选中自动登录框,则您可以正常验证他们的用户名和密码。如果成功,您可以为自动登录设置一个特殊的 cookie。
- 给这个特殊的 cookie 一个像“autologin”这样的名字,一个包含他们的用户名的值,以及他们用户数据的加盐 md5 哈希。类似于“user=username&hash=123456xyz.etc”。
- 当您下次见到该用户并希望自动登录时,您可以检查此特殊 cookie 并验证其内容。拆分用户名和哈希,然后根据用户名从数据库中提取帐户并重新执行 md5 以与 cookie 哈希数据进行比较。如果有效,您可以登录它们(即开始一个新会话)。
回答by Anthony
You should take their username, IP address, and some kind of hash (as zombat suggested), encrypt all of it (probably using Base64) and store the resulting string as their cookie. This way, someone can't spoof or steal the cookie, because even if they did, the decrypted IP address wouldn't match the IP address that the request was coming from. It's also better to use whitelists instead of dropping user input into a query.
您应该获取他们的用户名、IP 地址和某种哈希值(如 zombat 建议的那样),加密所有这些(可能使用 Base64)并将结果字符串存储为他们的 cookie。这样,某人就无法欺骗或窃取 cookie,因为即使他们这样做了,解密后的 IP 地址也不会与请求来自的 IP 地址匹配。最好使用白名单而不是将用户输入放入查询中。
So you'd get something like:
所以你会得到类似的东西:
//First see if the auto-login cookie exists and is valid:
if($_COOKIE['autologin']) {
$users_query = "SELECT username FROM users WHERE last_login < SUBDATE(CURDATE(),30)";
$users_results = mysql_query($users_query);
while($row = mysql_fetch_assoc($users_result)) {
$users = $row['username'];
}
$auto_cookie = $_COOKIE['autologin'];
$user_creds = explode("//", base64_decode($auto_cookie));
$user_name = $user_creds[0];
$user_IP = $user_creds[1];
$user_hash = $user_creds[2];
$username_check = (in_array($user_name, $users) ? true : false;
$userIP_check = ($user_IP = $_SERVER['REMOTE_ADDR']) ? true :false;
$so_far_so_good = ($username_check && $userIP_check) ? true : false;
if($so_far_so_good) {
$hash_query = "SELECT hash FROM userhash WHERE username = '$user_name'";
$hash_results = mysql_query($hash_query);
$all_clear = ($user_hash == mysql_result($hash_results,0)) ? true : false;
}
}
//Checks Login Data:
if($_POST) {
$users_query = "SELECT username FROM users";
$users_results = mysql_query($users_query);
while($row = mysql_fetch_assoc($users_result)) {
$users = $row['username'];
}
$username_check = (in_array($user_name, $users) ? true : false;
$password_check = password_check();
// I do not feel comfortable enough with encryption and authentication to suggest
// a method here. Suffice to say, you should have a strong password check system.
$all_clear = ($username_check && $password_check) ? true : false;
// You should only throw a log in error when they have attempted a login. Do not
// give hints at your authentication methods in auto-login section.
$set_cookie = ($all_clear && $_POST['set-auto']) ? true : false;
if($set_cookie) {
$new_hash = hash_maker();
// Again, look to the others for best hashing technique.
$raw_cookie_data = $user_name . "//" . $_SERVER['REMOTE_ADDR'] . "//" . $new_hash;
$enc_cookie_data = base64_encode($raw_cookie_data);
setcookie("autologin", $enc_cookie_data, time()+3600);
}
}
if($all_clear) {
echo "Welcome Back!";
}
else {
//print login form here...
}
回答by Puran Saini
We can create auto login using cookies in php , this feature is required in case you want to create web view of your website , as mobile user don't want to login every time they open your android app (web view of your web site. You can use the code below tom implement the auto-login on your php based website
我们可以在 php 中使用 cookie 创建自动登录,如果您想创建网站的 Web 视图,则需要此功能,因为移动用户不想每次打开您的 android 应用程序时都登录(您网站的 Web 视图。您可以使用下面的代码在基于 php 的网站上实现自动登录
<?php
session_start();
include(“connect.php”); // your mysql connect code
// code to read user name and password in cookies on client machine
if(isset($_COOKIE[“username”])) $email= $_COOKIE[“username”]; else $email=””;
if(isset($_COOKIE[“password”])) $pwd=$_COOKIE[“password”]; else $pwd=””;
// if cookies are set for login details then we compare the login details with database //and redirect the user directly to page after login so user is not required to input //login details and then click on login button
if ($email!=””)
{
$sql= “select * from members where username='”.$email.”‘ and user_pwd='”.$pwd.”‘”;
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$count = mysqli_num_rows($result);
if($count > 0 && $row[‘auto_login']==1)
{
$_SESSION[‘uname'] = $email;
$_SESSION[‘uid']=$row[‘id'];
setcookie (“username”,$email,time()+ 3600);
setcookie (“password”,$pwd,time()+ 3600);
header(‘Location:myhome.php');
}
}
?>
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>My Expense-Login</title>
<meta charset=”utf-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1″>
<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css”>
<script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js”></script>
<script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js”></script>
</head>
<body>
<?php include(“top-menu-login.php”); ?>
<div class=”container”>
<div class=”row”>
<div class=”col-md-3″></div>
<div class=”col-md-6″>
<h2 class=”text-center”>User Login</h2>
<div id=”message”></div>
<div class=”form-group”>
<label for=”email”>Email address:</label>
<!– here we check if cookies is set then auto fill the login details –>
<input type=”email” class=”form-control” id=”email” name=”email” value=”<?php if(isset($_COOKIE[“username”])) { echo $_COOKIE[“username”]; } ?>”>
</div>
<div class=”form-group”>
<label for=”pwd”>Password:</label>
<input type=”password” class=”form-control” id=”pwd” name=”pwd” value=”<?php if(isset($_COOKIE[“password”])) { echo $_COOKIE[“password”]; } ?>” >
</div>
<div class=”form-group ml-4″>
<label class=”form-check-label”>
<input class=”form-check-input” type=”checkbox” name=”remember” id=”remember” <?php if(isset($_COOKIE[“username”])) { echo “checked”; } ?>> Auto Login
</label>
<label class=”form-signup”>
<a href=”forgot-pass.php” class=”btn btn-light”> Forgot Passsword </a>
</label>
</div>
<button type=”button” class=”btn btn-primary” id=”btn-submit”>Submit</button>
<button type=”button” class=”btn btn-success” id=”btn-register”>Register</button>
</div>
<div class=”col-md-3″><br>
</div>
</div>
</div>
</body>
</html>

