search
HomeBackend DevelopmentPHP TutorialHow to write a secure user authentication system using PHP

How to write a secure user authentication system using PHP

Jul 06, 2023 pm 12:49 PM
SafetyUser AuthenticationPHP programming keywords:System writing

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

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 id="用户注册">用户注册</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>

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 id="用户登录">用户登录</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>

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

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!

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor