prepare("SELECT * FROM email_verifications WHERE verification_code = ? AND purpose = 'password_reset'"); $stmt->bind_param("s", $verification_code); $stmt->execute(); $result = $stmt->get_result(); $record = $result->fetch_assoc(); $stmt->close(); if (!$record) { $_SESSION['error'] = "Invalid or expired password reset code."; header("Location: password-reset.php?code=" . urlencode($verification_code)); exit; } // Check expiration $current_time = new DateTime(); $expires_at = new DateTime($record['expires_at']); if ($current_time > $expires_at) { $_SESSION['error'] = "Password reset code has expired."; header("Location: password-reset.php?code=" . urlencode($verification_code)); exit; } // Verify the username matches the record $stmt = $db->prepare("SELECT id, username FROM users WHERE id = ? AND username = ?"); $stmt->bind_param("is", $record['user_id'], $username); $stmt->execute(); $userData = $stmt->get_result()->fetch_assoc(); $stmt->close(); if (!$userData) { $_SESSION['error'] = "Username does not match our records."; header("Location: password-reset.php?code=" . urlencode($verification_code)); exit; } // Update the user's password $hashed_password = password_hash($new_password, PASSWORD_DEFAULT); $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?"); $stmt->bind_param("si", $hashed_password, $userData['id']); $stmt->execute(); $stmt->close(); // Remove the password reset record $stmt = $db->prepare("DELETE FROM email_verifications WHERE verification_code = ? AND purpose = 'password_reset'"); $stmt->bind_param("s", $verification_code); $stmt->execute(); $stmt->close(); $_SESSION['success'] = "Your password has been reset successfully. Please log in with your new password."; header("Location: login.php"); exit; } require_once 'includes/header.php'; ?>
' . htmlspecialchars($_SESSION['error']) . '
'; unset($_SESSION['error']); } ?>

Reset Password