gpt4 book ai didi

php - 获取用户 ID 以继续登录

转载 作者:行者123 更新时间:2023-11-29 22:24:41 24 4
gpt4 key购买 nike

我正在制作一个小网页,我想提取用户id,以便检查该帐户是否存在。我通过连接到 MySQL 数据库并检查该帐户是否存在来完成此操作。我对这一切都很陌生,只知道 PHP 和 MySQL 的绝对基础知识。这是我的login.php:

login.php

    <?php

$server = "fooServer";
$user = "foo";
$pass = "foo";
$db = "newsContent";
$conn = new mysqli($server, $user, $pass, $db);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
?>

<?php
$email = $_POST['email']; //Taken from my index.php
$password = $_POST['password']; //Taken from my index.php

/*I used this so as to extract the id. I then wanted to
proceed with the procedure if the id existed, and alert the user if it didn't*/
$sql = "SELECT id FROM fooTable WHERE username='$email' && password='$password'";

if ($conn->query($sql) === TRUE) {
echo "
<script>
alert('Login Successful');
window.location.href='news.php';
</script>";
} else {
<script>
alert('Login unuccessful. User account does not exist');
window.location.href='news.php';
</script>";
}
?>

对于经验丰富的程序员来说,这段代码可能看起来很可怕,我理解,但请不要提出建议。

最佳答案

每当您使用用户输入作为 SQL 查询的一部分时,您都会面临 SQL 注入(inject)漏洞的风险。虽然您可以使用准备好的语句或进行大​​量清理,但迄今为止我见过的最强大的方法是这样的:

function authenticate($email, $password) {

if (empty($email) || empty($password)) return false;

$auth = false;
$check = false;
$q1 = "SELECT * FROM user WHERE active = 1 ORDER BY email ASC";
$knownUsers = $this -> sql -> doMultiSelect($q1);

$checkUser = "";

foreach ($knownUsers AS $user){
if ($user ['email'] == $email) {
$check = true;
$checkUser = $user;
break;
}
if (substr($user['email'],0,1) > substr($email,0,1)) {
break;
}
}

if ($check) {
if ($checkUser['password'] == crypt($password, $email) ) {
$auth = true;
// do something with the user data
}
} else {
$this -> logActivity("failed login attempt for user ".$email);
}
return $auth;
}

显然,您需要根据您的需求进行一些调整。

这种方法永远不会将用户输入传递到数据库,而数据库仅用于读取。

请注意,这种方法对于数百甚至数千个用户来说已经足够了,但对于大量现有用户来说就不够了。

还有一点:您可能希望使用用户的 ID 进行进一步处理,但最好使用不易被猜到的内容。也许是用户电子邮件的 MD5 或类似的内容。

关于php - 获取用户 ID 以继续登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30376222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com