gpt4 book ai didi

php通过登录页面连接到数据库

转载 作者:行者123 更新时间:2023-11-29 04:19:26 25 4
gpt4 key购买 nike

我是 php 的新手,所以请原谅我的新代码,虽然我需要使用 php,但更习惯于 ASP.net,目前我有 php 页面连接到数据库,如果成功将值存储到由于不正确的字符串,cookie 会抛出这些错误消息

Warning: Illegal string offset 'Member_Username' in C:\xampp\htdocs\awm\includes\login.php on line 10

Warning: Illegal string offset 'Member_Password' in C:\xampp\htdocs\awm\includes\login.php on line 10

Notice: Trying to get property of non-object in C:\xampp\htdocs\awm\includes\login.php on line 13

这是我的代码:

<?php

try
{
$Username = $_POST['Username'];
$Password = $_POST['Password'];

$con = mysqli_connect('localhost','root','Password','Letting');

$query = "SELECT Member_Id, Member_Firstname, Member_Surname FROM Members WHERE Member_Username = '" . $Username['Member_Username'] . "' AND Password = '" . $Password['Member_Password']. "'";
$result = $con->query($query);

if($result->num_rows)
{
$row = $result->fetch_assoc();

$_SESSION['MemberId']=$row['Member_Id'];
$_SESSION['Firstname']=$row['Member_Firstname'];
$_SESSION['Surname']=$row['Member_Surname'];

if(isset($_POST['RememberMe']))
{
setcookie('login',$row['Member_Id'],time() +60*60*60*24*7);
}
else
{
$msg = 'Login failed';
}
}
}
catch(Exception $e)
{
echo $e->errorMessage();
}
?>

最佳答案

假设这些变量是字符串:

$Username = $_POST['Username'];
$Password = $_POST['Password'];

使用索引将它们作为数组调用/处理肯定会触发非法字符串偏移错误。这是哪一行:

$query = "SELECT Member_Id, Member_Firstname, Member_Surname FROM Members WHERE Member_Username = '" . $Username['Member_Username'] .  "' AND Password = '" . $Password['Member_Password']. "'";

既然 MySQLi 已经支持准备好的语句,为什么不利用它们呢,因为就目前而言,您很容易受到 SQL 注入(inject)的攻击。我不会添加直接连接 $Username$Password 的解决方案,但我会给出关于准备好的语句的粗略示例:

$query = 'SELECT Member_Id, Member_Firstname, Member_Surname 
FROM Members
WHERE Member_Username = ?
AND Password = ?';

$select = $con->prepare($query);
$select->bind_param('ss', $Username, $Password);
$select->execute();

if($select->num_rows > 0) {
// rest of codes
}

旁注:您似乎正在保存普通的裸密码,如果您可以使用它(PHP 5.5 或更高版本),我建议您应该使用 password_hash + password_verify处理您的登录模块以散列这些密码。如果你有 PHP 5.4 或更低版本并且不能使用内置的,那么已经有一个 compatibility pack library为此。

关于php通过登录页面连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29677715/

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