简体   繁体   English

使用php注册后自动登录

[英]Auto login after registration with php

From what I understood it may be,据我了解,可能是
session_start(); !isset($_SESSION['loggedin'])) and maybe few other lines !isset($_SESSION['loggedin']))以及其他几行

After the user registers successfully, I want him to be redirected to home.php用户注册成功后,我想让他重定向到home.php
Could you please show me an exact snippet?你能告诉我一个确切的片段吗?


register.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>';

    }
}
?>

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);
}
?>

To perform auto login after registration you need to follow these steps:要在注册后执行自动登录,您需要按照以下步骤操作:

  1. Make sure you start the session.确保您开始会话。 As I can see, you are already starting the session in main.php which is then included in register.php正如我所看到的,您已经在 main.php 中启动了会话,然后将其包含在 register.php 中
  2. After successful registration you need to populate the session variables in exactly the same way as you would do after successful login .成功注册后,您需要以与成功登录后完全相同的方式填充会话变量。 You can receive the auto-generated ID by calling lastInsertId() method.您可以通过调用lastInsertId()方法接收自动生成的 ID。 The username comes from the form.用户名来自表单。 The role is the default one, so you can hardcode it or read from database.该角色是默认角色,因此您可以对其进行硬编码或从数据库中读取。
     // 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. In the above example, I added header('Location: home.php');在上面的例子中,我添加了header('Location: home.php'); after successful registration.注册成功后。 Adjust it according to your needs.根据您的需要进行调整。 Once the session variables are populated, you can redirect the user to the home page where the check for isset($_SESSION['id']) should take place.填充会话变量后,您可以将用户重定向到应检查isset($_SESSION['id'])的主页。 This will tell you whether the user is logged in or not.这将告诉您用户是否已登录。

I am not sure what is the purpose of $_SESSION['loggedin'] as it seems to be true in all cases.我不确定$_SESSION['loggedin']的目的是什么,因为在所有情况下似乎都是如此。 Maybe you can remove it from your code.也许你可以从你的代码中删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM