簡體   English   中英

使用php注冊后自動登錄

[英]Auto login after registration with php

據我了解,可能是
session_start(); !isset($_SESSION['loggedin']))以及其他幾行

用戶注冊成功后,我想讓他重定向到home.php
你能告訴我一個確切的片段嗎?


注冊.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>';

    }
}
?>

主文件

<?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']的目的是什么,因為在所有情況下似乎都是如此。 也許你可以從你的代碼中刪除它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM