Home > Backend Development > PHP Tutorial > How to write a secure user authentication system using PHP

How to write a secure user authentication system using PHP

WBOY
Release: 2023-07-06 12:50:01
Original
1308 people have browsed it

How to use PHP to write a secure user authentication system

Introduction:
In modern Internet applications, user authentication is a crucial component. A secure and reliable user authentication system is critical to protecting user data and application security. Therefore, it is very important to learn how to write a secure user authentication system using PHP. This article will introduce how to implement a secure user authentication system in PHP and provide code examples.

1. Preparation work
Before starting to write the user authentication system, you need to prepare the following environment and tools:

  1. A Web server with PHP installed;
  2. A database management system, such as MySQL;
  3. A text editor, such as Sublime Text or Visual Studio Code.

2. Database design
Before we start writing code, we need to design the database schema. A typical user authentication system requires the following tables:

  1. User table (users): stores user information, such as user name, password, etc.;
  2. Role table (roles): stores users Role information;
  3. Permissions table (permissions): stores user permission information;
  4. User role association table (users_roles): stores the association between users and roles;
  5. Role permission association table (roles_permissions): stores the association between roles and permissions.

You can use the following SQL statements to create the above tables:

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username VARCHAR(255) NOT NULL UNIQUE,
    password VARCHAR(255) NOT NULL
);

CREATE TABLE roles (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL UNIQUE
);

CREATE TABLE permissions (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(255) NOT NULL UNIQUE
);

CREATE TABLE users_roles (
    user_id INT NOT NULL,
    role_id INT NOT NULL,
    PRIMARY KEY (user_id, role_id),
    FOREIGN KEY (user_id) REFERENCES users (id),
    FOREIGN KEY (role_id) REFERENCES roles (id)
);

CREATE TABLE roles_permissions (
    role_id INT NOT NULL,
    permission_id INT NOT NULL,
    PRIMARY KEY (role_id, permission_id),
    FOREIGN KEY (role_id) REFERENCES roles (id),
    FOREIGN KEY (permission_id) REFERENCES permissions (id)
);
Copy after login

3. User registration
Implement the function of user registration, including verifying user name and password, inserting user information into User table is medium. The following is a code example for a simple user registration page:

<?php
session_start();
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // 验证用户名和密码
    if (empty($username) || empty($password)) {
        $error = '请输入用户名和密码';
    } else {
        // 将用户信息插入到用户表中
        // ...
    }
}
?>

<!DOCTYPE html>
<html>
<body>

<h2>用户注册</h2>

<form method="POST" action="">
  用户名:<input type="text" name="username"><br>
  密码:<input type="password" name="password"><br>
  <input type="submit" value="注册">
</form>

<p><?php echo $error; ?></p>

</body>
</html>
Copy after login

4. User login
Implements the user login function, including verifying the user name and password entered by the user. After successful verification, the user information is stored in the session ( session) for subsequent use. The following is a code example of a simple user login page:

<?php
session_start();
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // 根据用户名查询用户信息
    // ...

    // 验证用户名和密码
    if ($user && password_verify($password, $user['password'])) {
        // 将用户信息存储在会话中
        $_SESSION['user'] = $user;
        // 跳转到用户首页
        header('Location: user_home.php');
        exit;
    } else {
        $error = '用户名或密码不正确';
    }
}
?>

<!DOCTYPE html>
<html>
<body>

<h2>用户登录</h2>

<form method="POST" action="">
  用户名:<input type="text" name="username"><br>
  密码:<input type="password" name="password"><br>
  <input type="submit" value="登录">
</form>

<p><?php echo $error; ?></p>

</body>
</html>
Copy after login

5. User permission verification
After the user successfully logs in, the user needs to be verified for permission to ensure that the user can only access the areas to which he or she has permission. page. The following is a simple permission verification code example:

<?php
session_start();

// 检查用户是否登录
if (!isset($_SESSION['user'])) {
    // 跳转到登录页面
    header('Location: login.php');
    exit;
}

// 检查用户是否具备权限
function checkPermission($permission) {
    $user = $_SESSION['user'];
    // 根据用户角色查询用户具备的权限
    // ...

    // 验证用户是否具备权限
    if (in_array($permission, $user['permissions'])) {
        return true;
    } else {
        return false;
    }
}
?>
Copy after login

Summary:
Through the above example code, we understand how to use PHP to write a basic secure user authentication system. In practical applications, attention must also be paid to filtering and verifying user input, encrypting and storing user passwords, and handling the password retrieval process to improve system security and user experience. At the same time, the user authentication system is also a dynamic process and needs to be continuously improved and perfected according to actual needs.

The above is the detailed content of How to write a secure user authentication system using PHP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template