Home Backend Development PHP Tutorial How to use PHP functions to implement multi-level role and permission management for user login and logout?

How to use PHP functions to implement multi-level role and permission management for user login and logout?

Jul 24, 2023 pm 09:49 PM
Log out User login authority management multi-level roles

How to use PHP functions to implement multi-level role and permission management for user login and logout?

When developing a website, user login and logout are a very common and important function. As website functions expand, multi-level role and permission management is usually required to ensure that different users have different operating permissions. This article will introduce how to use PHP functions to achieve this functionality and provide code examples.

First, we need to create a database table to store user information. The table structure is as follows:

CREATE TABLE users (
    id INT(11) AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(100) NOT NULL,
    password VARCHAR(100) NOT NULL,
    role VARCHAR(50) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Copy after login

Among them, username stores the user name, password stores the hash value of the password, role stores the user role,created_at Stores user creation time.

Next, we need to write PHP code for login and logout functions. The first is the login function:

function login($username, $password) {
    // 从数据库中查询用户信息
    $query = "SELECT * FROM users WHERE username = '$username'";
    $result = mysqli_query($conn, $query);
    
    if (mysqli_num_rows($result) == 1) {
        $user = mysqli_fetch_assoc($result);

        // 验证密码
        if (password_verify($password, $user['password'])) {
            // 设置用户登录状态
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];

            return true;
        }
    }

    return false;
}
Copy after login

The above code first queries whether the user name exists in the database. If it exists, the correctness of the password is verified through the password_verify function. If the verification is passed, the user information will be stored in $_SESSION to realize user login.

Next is the code for the logout function:

function logout() {
    // 销毁session
    session_unset();
    session_destroy();
}
Copy after login

The above code destroys the current $_SESSION by calling the session_unset function and the session_destroy function .

Through the above code, we can implement basic user login and logout functions. But in order to achieve multi-level role and permission management, we also need to provide corresponding functional interfaces.

First, we need to write a function that checks user permissions:

function checkPermission($requiredRole) {
    if (isset($_SESSION['role']) && $_SESSION['role'] == $requiredRole) {
        return true;
    } else {
        return false;
    }
}
Copy after login

The above code will check whether the current user's role meets the required roles. If satisfied, return true, otherwise return false.

Next, we can implement corresponding permission control by calling the checkPermission function.

if (checkPermission('admin')) {
    // 执行管理员操作
} elseif (checkPermission('user')) {
    // 执行普通用户操作
} else {
    // 无权限操作
}
Copy after login

The above code will perform corresponding operations based on the user's role. If the user role is an administrator, administrator operations are performed; if the user role is an ordinary user, ordinary user operations are performed; if the user does not have permissions, operations without permissions are performed.

In summary, through the above code examples, we use PHP functions to implement multi-level role and permission management for user login and logout. When developing a website, this method can achieve flexible user permission control and ensure the security of the website.

The above is the detailed content of How to use PHP functions to implement multi-level role and permission management for user login and logout?. For more information, please follow other related articles on the PHP Chinese website!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Can I cancel my Xiaohongshu account and recover it? What will happen after Xiaohongshu is canceled? Can I cancel my Xiaohongshu account and recover it? What will happen after Xiaohongshu is canceled? Mar 23, 2024 am 11:11 AM

With the rapid development of social media, Xiaohongshu has become one of the popular platforms for users to share their life and shopping experiences. However, sometimes we may need to cancel our Xiaohongshu account, whether for personal reasons, security concerns, or other considerations. However, once logged out, can we restore the account? Let’s take a closer look. 1. Can I recover my Xiaohongshu account after canceling it? Let’s take a look at Xiaohongshu’s account cancellation process. When users decide to cancel their account, they can complete the logout operation by entering the "Settings" page of the Xiaohongshu app, selecting "Account and Security", and then clicking the "Cancel Account" button. After confirming the cancellation, Xiaohongshu will process the user's account and delete relevant personal information and publications.

How to cancel Alipay account? Steps to cancel Alipay account. How to cancel Alipay account? Steps to cancel Alipay account. Feb 22, 2024 pm 03:40 PM

You can log out on the account logout interface in Account and Security. Tutorial Applicable Model: iPhone13 System: iOS15.5 Version: Alipay 10.2.8 Analysis 1 Click the small gear icon in the upper right corner of Alipay's My interface. 2Click [Account and Security] in the pop-up window. 3Click [Security Center] on the account and security interface. 4Click [Account Logout] on the Security Center interface. 5Click [Cancel Now] and complete the relevant operations according to the instructions to log out of Alipay. Supplement: If Alipay is canceled, can I still apply for it back? 1 If Alipay is canceled, you can reapply, but the original account cannot be restored. If the Alipay account is successfully closed, it cannot be restored and the original rights and services of the account will be invalid. this means

How to cancel China Mobile card How to cancel China Mobile card Mar 14, 2024 pm 06:25 PM

How to cancel the China Mobile card? In China Mobile, you can directly cancel the phone card. Most users do not know how to cancel the mobile card. Next is the graphic tutorial on how to cancel the China Mobile card brought by the editor for users who are interested. Come and take a look! How to cancel the China Mobile card 1. First open the China Mobile APP, click the [My] area in the lower right corner of the main page and select the [Settings] button in the upper right corner; 2. Then jump to the settings function page, select the [Account and Security] option and click; 3. Then go to the account and security service page and find the [Logout Service] function; 4. Finally, on the page shown in the picture below, check the square box and click [Confirm Application] to log out.

How to cancel Douban account? Douban account cancellation operation process! How to cancel Douban account? Douban account cancellation operation process! Mar 15, 2024 pm 06:40 PM

1. How to cancel the Douban account? Douban account cancellation operation process! 1. Click the button in the upper left corner of the Douban app and select Settings. 2. In the settings interface, select the information and account options. 3. Then enter the information and account settings page, and click Douban Security Center. 4. After jumping to the Douban Security Center interface, click to log out of the account. 5. Finally, in deleting the account, click the Continue to log out button to complete the account logout.

Can I get it back if I cancel Xiaohongshu? Does the cancellation take effect immediately? Can I get it back if I cancel Xiaohongshu? Does the cancellation take effect immediately? Mar 08, 2024 am 08:04 AM

In recent years, with the rise of social media, more and more people choose to share their life details on the Internet. As a social platform with the theme of shopping reviews and life sharing, Xiaohongshu is deeply loved by young people. However, sometimes we may encounter situations that require us to cancel our Xiaohongshu account. So, if Xiaohongshu is canceled, can I still get it back? 1. If Xiaohongshu has been canceled, can I still get it back? cannot. When we decide to cancel our Xiaohongshu account, the first thing we need to know is that the cancellation operation is irreversible. Once the cancellation is successful, the account cannot be restored. Therefore, we must think twice before proceeding with the logout operation. On the official help page provided by Xiaohongshu, they clearly state that once a user deletes their account, the corresponding data and content will be permanently deleted.

How to implement data sharing and permission management in React Query? How to implement data sharing and permission management in React Query? Sep 27, 2023 pm 04:13 PM

How to implement data sharing and permission management in ReactQuery? Advances in technology have made data management in front-end development more complex. In the traditional way, we may use state management tools such as Redux or Mobx to handle data sharing and permission management. However, after the emergence of ReactQuery, we can use it to deal with these problems more conveniently. In this article, we will explain how to implement data sharing and permissions in ReactQuery

How to use the Layui framework to develop a permission management system that supports multi-user login How to use the Layui framework to develop a permission management system that supports multi-user login Oct 27, 2023 pm 01:27 PM

How to use the Layui framework to develop a permission management system that supports multi-user login Introduction: In the modern Internet era, more and more applications need to support multi-user login to achieve personalized functions and permission management. In order to protect the security of the system and the privacy of data, developers need to use certain means to implement multi-user login and permission management functions. This article will introduce how to use the Layui framework to develop a permission management system that supports multi-user login, and give specific code examples. Preparation before starting development

How to log out or shut down the system in Debian 11 How to log out or shut down the system in Debian 11 Dec 27, 2023 pm 02:22 PM

How to shut down the system in Debian11? Let’s take a look at the specific operations with the editor. Method 1: Click [All Apps] - [Log Out]. In the pop-up interface, click [Shut Down]. Method 2: Execute the following command in the terminal: sudoshutdown-hnow

See all articles