Home  >  Article  >  Backend Development  >  How to implement user registration in php? Step sharing

How to implement user registration in php? Step sharing

PHPz
PHPzOriginal
2023-03-27 16:16:251423browse

Today, we will discuss a common question: how to implement user registration function in PHP. Whether you are developing a website based on the web or building an application, implementing user registration functionality is a must.

Usually, the implementation of the user registration function requires the following steps:

  • Create a registration form

  • After the user submits When forming a form, verify the user's input

  • If the input is legal, save the username and password

  • Send an email for confirmation

  • Create a login page, and when the user enters the correct username and password, let the user log in to the system

Below, we will introduce how to implement these functions step by step .

  1. Create registration form

First, we need to create a form on the front end to allow users to fill in the necessary information. Typically the registration form includes the following:

  • Username
  • E-mail address
  • Password
  • Confirm password

For these inputs, we can use HTML to create a form, namely:

<form method="post" action="register.php">
    <label for="username">用户名</label>
    <input type="text" name="username" required>

    <label for="email">电子邮件</label>
    <input type="email" name="email" required>

    <label for="password">密码</label>
    <input type="password" name="password" required>

    <label for="confirm_password">确认密码</label>
    <input type="password" name="confirm_password" required>

    <input type="submit" value="注册">
</form>

Note that we set the action attribute of the form to "register.php", which means that when the user submits the form, it will be sent POST request to register.php page.

  1. Verify the user's input when the user submits the form

Next, we need to write code in PHP to validate the user's input data . In the register.php page, we need to:

  • Get the data entered by the user
  • Verify whether the user name meets the requirements (for example: whether the length is reasonable, whether it is unique, etc.)
  • Verify that the email address is valid and unique
  • Verify that the password and confirmation password match
  • If all verifications pass, save the user's data

Here is a simple example:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // 获取用户输入的数据
    $username = $_POST[&#39;username&#39;];
    $email = $_POST[&#39;email&#39;];
    $password = $_POST[&#39;password&#39;];
    $confirm_password = $_POST[&#39;confirm_password&#39;];

    // 验证用户名是否符合要求
    if (strlen($username) < 6) {
        echo "用户名长度必须大于 6 个字符";
        exit;
    }

    // 验证电子邮件地址是否有效和唯一
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "电子邮件地址无效";
        exit;
    }

    // 判断用户名和电子邮件地址是否唯一

    // 验证密码和确认密码是否匹配
    if ($password != $confirm_password) {
        echo &#39;两次输入的密码不一致,请重新输入&#39;;
        exit;
    }

    // 保存用户的数据
    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    // 对密码进行哈希加密后保存

    // 发送一封确认邮件进行验证

    // 跳转到登录页面
    header(&#39;Location: login.php&#39;);
}
?>
  1. Save username and password

In the register.php page, we need to add the user’s username and The hashed password is saved to the database. Normally, we use the SQL INSERT statement, that is:

// 建立一个连接
$conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");

// 创建一个 SQL INSERT 语句
$sql = "INSERT INTO users (username, password) VALUES ('$username', '$hashed_password')";

// 执行 SQL 语句
mysqli_query($conn, $sql);

Please note that the above code is a simple example. In actual situations, we need to handle database operations more strictly and safely.

  1. Send an email for confirmation

In order to ensure that the registered user’s email address is valid and authentic, we can register the user A confirmation email will be sent immediately. The email contains a unique link that users need to click to confirm their email address.

In order to achieve this function, we need to use PHP's email sending function, such as PHPMailer. Here is a simple example:

// 导入 PHPMailer 库
require_once "PHPMailer/PHPMailer.php";
require_once "PHPMailer/SMTP.php";
require_once "PHPMailer/Exception.php";

// 创建一个新的 PHPMailer 实例
$mail = new PHPMailer\PHPMailer\PHPMailer();

// 使用 SMTP 服务器发送邮件
$mail->isSMTP();

// 设置邮件服务器地址和端口
$mail->Host = "smtp.example.com";
$mail->SMTPAuth = true;
$mail->Username = "your-email@example.com";
$mail->Password = "your-email-password";
$mail->SMTPSecure = "tls";
$mail->Port = 587;

// 设置发件人和收件人
$mail->setFrom('your-email@example.com', 'Your Name');
$mail->addAddress($email, $username);

// 设置邮件主题和内容
$mail->Subject = '确认您的电子邮件地址';
$mail->Body = "click to confirm your email address: https://your-website.com/confirm.php?email=$email&code=$confirmation_code";

// 发送邮件
if (!$mail->send()) {
    echo '邮件发送失败';
    exit;
}
  1. Create a login page

Finally, we need to provide the user with a login page to allow them to use their Log in to the system with your username and password. Typically, we create a form to receive user input in a similar manner to the registration page. At the same time, we need to verify the password saved in the database to ensure that the password entered by the user is correct. Here is a simple example:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = $_POST[&#39;username&#39;];
    $password = $_POST[&#39;password&#39;];

    // 验证用户名和密码是否匹配
    $conn = mysqli_connect("localhost", "my_user", "my_password", "my_db");
    $sql = "SELECT * FROM users WHERE username=&#39;$username&#39;";
    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) == 1) {
        $row = mysqli_fetch_assoc($result);
        if (password_verify($password, $row[&#39;password&#39;])) {
            echo "登录成功";
            exit;
        }
    }

    echo "用户名或密码错误,请重试";
}
?>
<form method="post" action="login.php">
    <label for="username">用户名</label>
    <input type="text" name="username" required>

    <label for="password">密码</label>
    <input type="password" name="password" required>

    <input type="submit" value="登录">
</form>

Summary

Implementing user registration functionality in PHP requires multiple steps. First, we need to create a form on the front end that allows users to enter registration information. We then need to validate the data entered by the user in the register.php page and save the username and password to the database. In order to ensure that the email address entered by the user is valid and authentic, we can do this by sending a confirmation email. Finally, we need to provide a login page for users, allowing them to log into the system using their username and password. Good luck with your implementation!

The above is the detailed content of How to implement user registration in php? Step sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn