使用 php 注册后自动登录

Auto login after registration with php

据我了解可能是,
session_start(); !isset($_SESSION['loggedin'])) 可能还有其他几行

用户注册成功后,我想让他跳转到home.php
你能告诉我一个确切的片段吗?


register.php

<?php
include 'main.php';
// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['username'], $_POST['password'], $_POST['cpassword'], $_POST['email'])) {
    // Could not get the data that should have been sent.
    exit('<div class="error form">Please complete the registration form!</div>');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
    // One or more values are empty.
    exit('<div class="error form">Please complete the registration form!</div>');
}
// Check to see if the email is valid.
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    exit('<div class="error form">Email is not valid!</div>');
}
// Username must contain only characters and numbers.
if (!preg_match('/^[a-zA-Z0-9]+$/', $_POST['username'])) {
    exit('<div class="error form">Username is not valid!</div>');
}
// Password must be between 5 and 20 characters long.
if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
    exit('<div class="error form">Password must be between 5 and 20 characters long!</div>');
}
// Check if both the password and confirm password fields match
if ($_POST['cpassword'] != $_POST['password']) {
    exit('<div class="error form">Passwords do not match!</div>');
}
// Check if the account with that username already exists
$stmt = $pdo->prepare('SELECT id, password FROM accounts WHERE username = ? OR email = ?');
$stmt->execute([ $_POST['username'], $_POST['email'] ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// Store the result so we can check if the account exists in the database.
if ($account) {
    // Username already exists
    echo '<div class="error form">Username and/or email exists!</div>';
} else {
    // Username doesn't exist, insert new account
    $stmt = $pdo->prepare('INSERT INTO accounts (username, password, email, activation_code) VALUES (?, ?, ?, ?)');
    // We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $uniqid = account_activation ? uniqid() : 'activated';
    $stmt->execute([ $_POST['username'], $password, $_POST['email'], $uniqid ]);
    if (account_activation) {
        // Account activation required, send the user the activation email with the "send_activation_email" function from the "main.php" file
        send_activation_email($_POST['email'], $uniqid);
        echo 'Please check your email to activate your account!';
    } else {
        echo '<div class="success form">You have successfully registered, you can now login!</div>';

    }
}
?>

main.php

<?php
// The main file contains the database connection, session initializing, and functions, other PHP files will depend on this file.
// Include thee configuration file
include_once 'config.php';
// We need to use sessions, so you should always start sessions using the below code.
session_start();
// No need to edit below
try {
    $pdo = new PDO('mysql:host=' . db_host . ';dbname=' . db_name . ';charset=' . db_charset, db_user, db_pass);
} catch (PDOException $exception) {
    // If there is an error with the connection, stop the script and display the error.
    exit('Failed to connect to database!');
}
// The below function will check if the user is logged-in and also check the remember me cookie
function check_loggedin($pdo, $redirect_file = 'index.php') {
    // Check for remember me cookie variable and loggedin session variable
    if (isset($_COOKIE['rememberme']) && !empty($_COOKIE['rememberme']) && !isset($_SESSION['loggedin'])) {
        // If the remember me cookie matches one in the database then we can update the session variables.
        $stmt = $pdo->prepare('SELECT * FROM accounts WHERE rememberme = ?');
        $stmt->execute([ $_COOKIE['rememberme'] ]);
        $account = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($account) {
            // Found a match, update the session variables and keep the user logged-in
            session_regenerate_id();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $account['username'];
            $_SESSION['id'] = $account['id'];
            $_SESSION['role'] = $account['role'];
        } else {
            // If the user is not remembered redirect to the login page.
            header('Location: ' . $redirect_file);
            exit;
        }
    } else if (!isset($_SESSION['loggedin'])) {
        // If the user is not logged in redirect to the login page.
        header('Location: ' . $redirect_file);
        exit;
    }
}
// Send activation email function
function send_activation_email($email, $code) {
    $subject = 'Account Activation Required';
    $headers = 'From: ' . mail_from . "\r\n" . 'Reply-To: ' . mail_from . "\r\n" . 'Return-Path: ' . mail_from . "\r\n" . 'X-Mailer: PHP/' . phpversion() . "\r\n" . 'MIME-Version: 1.0' . "\r\n" . 'Content-Type: text/html; charset=UTF-8' . "\r\n";
    $activate_link = activation_link . '?email=' . $email . '&code=' . $code;
    $email_template = str_replace('%link%', $activate_link, file_get_contents('activation-email-template.html'));
    mail($email, $subject, $email_template, $headers);
}
?>

要在注册后执行自动登录,您需要执行以下步骤:

  1. 确保开始会话。如我所见,您已经在 main.php 中开始会话,然后包含在 register.php
  2. 成功注册后,您需要在 中填充会话变量,方法与成功登录后 完全相同。您可以通过调用 lastInsertId() 方法接收自动生成的 ID。用户名来自表单。该角色是默认角色,因此您可以对其进行硬编码或从数据库中读取。
    // Username doesn't exist, insert new account
    $stmt = $pdo->prepare('INSERT INTO accounts (username, password, email, activation_code) VALUES (?, ?, ?, ?)');
    // We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $uniqid = account_activation ? uniqid() : 'activated';
    $stmt->execute([ $_POST['username'], $password, $_POST['email'], $uniqid ]);
    
    // Login in the user
    session_regenerate_id();
    $_SESSION['loggedin'] = TRUE;
    $_SESSION['name'] = $_POST['username'];
    $_SESSION['id'] = $pdo->->lastInsertId();
    $_SESSION['role'] = 'the default role';
    
    if (account_activation) {
        // Account activation required, send the user the activation email with the "send_activation_email" function from the "main.php" file
        send_activation_email($_POST['email'], $uniqid);
        echo 'Please check your email to activate your account!';
    } else {
        header('Location: home.php');
        exit;
    }
    
  3. 在上面的例子中,我在注册成功后添加了header('Location: home.php');。根据您的需要进行调整。填充会话变量后,您可以将用户重定向到主页,在主页上应该检查 isset($_SESSION['id'])。这将告诉您用户是否已登录。

我不确定 $_SESSION['loggedin'] 的目的是什么,因为它似乎在所有情况下都是正确的。也许您可以将其从您的代码中删除。