您的代码中没有对用户输入进行净化,这是登录系统中必须的,请在您的登录表单后尝试。
信息:我不使用 PDO,$con是MYSQLI连接。
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
您的站点应设置为仅 https,如果忽略此链接:htaccess redirect to https://www,您应该为能够成功登录的用户提供安全会话 cookie 或安全持久 cookie。本段下方的代码应位于页面顶部的任何 html 之前。此示例适用于时间相关的持久性 https 安全 cookie,设置为 1 天后将过期。您可以使用会话 cookie,但我发现如果人们经常访问您的网站,这会让他们很恼火,如果他们关闭并重新打开浏览器或标签,他们不想在同一天再次登录。
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
上面的代码将使用一个函数设置一个安全的cookie,因为你只希望它在成功登录后触发。 cookie 的名称确实应该是随机且唯一的,基于 microtime 的东西会很好用。确保它不是可以识别用户的重要内容!
重要提示: 供参考的 cookie 名称应在创建帐户时创建并添加到用户表中,以便您可以识别用户并表示他们的登录详细信息。
标准安全措施还应包括一个单独的表,其中包含登录者的 ip、时间、日期和用户名。如果您的站点繁忙,该表将很快填满,因此您可以设置一个 cron 作业来清理旧记录以保留缩小尺寸,在这种情况下,您需要为 datetime 添加一列来标识记录的年龄。
正在处理登录...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
正在检索 cookie 以验证用户身份...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
获取IP的链接如下:How to get the client IP address in PHP