无法将登录表单连接到 MySQL 数据库
此查询涉及实现根据 MySQL 数据库进行验证的用户登录功能。用户期望输入用户名和密码,该用户名和密码应根据数据库中存储的凭据进行验证。不幸的是,虽然表单提交没有错误,但并没有实现想要的功能。
这个问题的根本原因在于缺乏针对 SQL 注入攻击的保护以及不安全在数据库中以纯文本形式存储密码。为了解决这些问题,建议:
Register.php:
<code class="php">// Replace previous code with the following: session_start(); if (isset($_SESSION['userid'])) { // Redirect to safe page } if (isset($_POST['register'])) { $email = $_POST['email']; $password = $_POST['password']; // Cleartext password from user // New code for password hashing $hashed_password = password_hash($password, PASSWORD_DEFAULT); // Database connection and query $host = "localhost"; $dbname = "database_name"; $user = "username"; $pass = "password"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("INSERT INTO user_accounts (email, password) VALUES (?, ?)"); $stmt->execute([$email, $hashed_password]); // Redirect to login page $conn = null; } catch (PDOException $e) { throw $e; } }</code>
Login.php:
<code class="php">// Replace previous code with the following: session_start(); if (isset($_SESSION['userid'])) { // Redirect to safe page } if (isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['password']; // Cleartext password from user // Database connection and query $host = "localhost"; $dbname = "database_name"; $user = "username"; $pass = "password"; try { $conn = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Get hashed password from database $stmt = $conn->prepare("SELECT password FROM user_accounts WHERE email = ?"); $stmt->execute([$email]); $hashed_db_password = $stmt->fetchColumn(); if (password_verify($password, $hashed_db_password)) { // User authenticated successfully $_SESSION['userid'] = true; // Redirect to safe page } else { // Authentication failed } $conn = null; } catch (PDOException $e) { throw $e; } }</code>
通过这些代码修改,用户登录现在应该通过与 MySQL 数据库安全交互来正常运行,从而防止SQL注入攻击和用户密码泄露。
以上是为什么我的登录表单无法连接到我的 MySQL 数据库?的详细内容。更多信息请关注PHP中文网其他相关文章!