無法將登入表單連接到 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中文網其他相關文章!