PHP 登录脚本仅适用于 mysql 已知的用户名

标签 php mysql authentication

该脚本应该获取提交表单的一些变量。然后它应该从数据库中检查它们,看看密码和用户名是否匹配,如果不匹配,它应该将它们发送回登录页面。

我已经尝试让它检查用户名是否存在:

$this = "Select name from user where name = '".$_POST['name']"'";

$query = mysqli_query($conn,$this);

while( $row = mysqli_fetch_assoc($query)){

if (empty($row['name']){

 do this;

}

}

但仍然有一个空白页。

<?php
include "private/dbconnection.inc.php";

$conn = mysqli_connect($servername, $username, $password, $db);

if(!$conn){
  die ("Verbindung fehlgeschlagen: ". mysqli_connect_error());
}

$selectpw = "SELECT * from user where name = '".$_POST['name']." ' ";
$pwcheck = mysqli_query($conn,$selectpw);
$selectname = "SELECT name from user where name = '".$_POST['name']."'";
$namecheck = mysqli_query($conn,$selectname);
while ( $row = mysqli_fetch_assoc($pwcheck)){
  if ( $_POST['password'] === $row['password'] && $_POST['name'] === $row['name'] ){
header("Location:https://myhost.de/xxx/this/user.php");
}
else{
  header("Location:https://myhost.de/xxxx/prototyp1/");
}
}
mysqli_close($conn);
?>

脚本应检查用户是否有效登录,如果无效,则应将其发送回登录。如果他有效,他就会进入另一个页面。

但它只适用于 mysql 知道的用户名,而其他用户名则卡在 php 页面上,并且只显示空白屏幕。

最佳答案

正如 Obsidian 所说,您的代码可能容易受到 SQL 注入(inject)的攻击,因此更适合使用 PDO。这可以像下面的基本代码示例一样实现。

<?php
include "private/dbconnection.inc.php";

try {
    $db = new PDO('host=' . $server_name . ';dbname=' . $database . 'charset=utf-8;', $username, $password);
}
catch(PDOException $e)
{
    throw $e; // Throw the PDOException if something failed
}

if(isset($_POST['username']) && isset($_POST['password']))
{
    if(!empty($_POST['username'] && !empty($_POST['username'])
    {
        $query = $db->prepare('SELECT password FROM users WHERE username = ?');

        $query->bindParam(1, trim($_POST['username']));

        if($query->execute())
        {
            $password = $query->fetchColumn();

            if($_POST['password'] == $password)
            {
                header('Location: https://myhost.de/xxx/this/user.php');
            } else {
                header('Location: https://myhost.de/xxxx/prototyp1/');
            }
        }
    }
}

?>

关于PHP 登录脚本仅适用于 mysql 已知的用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138399/

相关文章:

php - Laravel Eloquent ,当一行满足 2 个条件时,如何从查询中排除行?

Php mail() 打破 650 个字符长的 Url

php - 如何列出 pecl 包的所有版本

PHP 数字清理正则表达式

authentication - 如何在Flutter中使用流转换器根据另一个输入字段的值验证输入

c# - Q : SignalR authentication with . NET 客户端在本地工作但在服务器上不工作

php与mysql的连接问题 - macbook pro

mysql - WHERE IN 与 Doctrine 2 DBAL

c# - 将 Entity Framework 的多对多关系保存到 MySQL

php - 如何通过 iframe 调用验证第三方网站