我使用 php 创建了一个登录脚本,并使用 MySQL 数据库来存储用户数据。
一切正常,直到我知道我的一个 friend (他的帐户也像我一样在数据库中创建)调用我并说我的个人资料已自动加载到他的手机上。如果没有使用各自的凭据填写登录表单,就无法创建我的 session 数据或任何人的 session ,这怎么可能!?
帮我解决这个问题!由于这是一个涉及用户数据安全的主要循环,未经他们的同意,它怎么可能从其他人的手机上访问!!
通过 login.php 创建 session
session_start();
if (isset($_POST['email']) and isset($_POST['password'])){
$email = $_POST['email'];
$password = $_POST['password'];
$query = "SELECT * FROM `users` WHERE email='$email' and password='$password'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_num_rows($result) > 0){
$_SESSION['email'] = $email;
$_SESSION['id'] = $id;
echo "You are logged in.";
header("Location: index.php?log=success");
unset($_POST);
}
else{
echo " Something went wrong ";
}
}
最佳答案
您正在分配 $_SESSION['id']
值为 $id
但是您的代码中没有任何地方指定 $id
的值是。这就是导致您的 session 混淆的原因,因为每个人都被赋予相同的空 ID。
从数据库中获取实际的用户 ID 并在 $_SESSION['id']
中使用该值你的问题就解决了。请参见下面的示例:
/* Start the session */
session_start();
/* Check if the user has submitted the login form $_POST */
if (isset($_POST['email']) and isset($_POST['password'])){
/* Get the values of $_POST */
$email = $_POST['email'];
$password = $_POST['password'];
/* Create the SQL query - Note: you should use bindings to prevent SQL injection */
$query = "SELECT * FROM `users` WHERE email='$email' and password='$password'";
/* Get the MySQL result */
$result = mysql_query($query) or die(mysql_error());
/* Check if the user was found */
if(mysql_num_rows($result) > 0){
/* Get the User ID from the database */
while($row = mysql_fetch_assoc($result)){
$id = $row['THE NAME OF YOUR ID COLUMN']; // replace with the name of your ID column in your DB
}
/* Set the session values */
$_SESSION['email'] = $email;
$_SESSION['id'] = $id;
/* Print output */
echo "You are logged in.";
/* Redirect to login page */
header("Location: index.php?log=success");
/* Unset POSTS */
unset($_POST);
} else {
/* Show login error message */
echo " Something went wrong ";
}
}
此外,您的代码目前容易受到 SQL 注入(inject)攻击。为了防止此类攻击,我建议您将参数绑定(bind)到 SQL 查询,而不是直接输入它们。 SQL Injection Info
关于php - 我的网站自动创建保存在数据库中的用户 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56240279/