How to use PHP to implement permission control functions
Permission control is a common web development requirement, which allows web applications to provide different access rights to different users. In PHP, permission control can be accomplished in a variety of ways. This article will focus on using Session and database to achieve permission control.
1. Use Session to implement permission control
Session is a state management technology commonly used in Web development. By saving user information in Session, we can use it on multiple pages of the application. share this information. In order to implement permission control, we can save the user's information in the Session after the user logs in, and check whether the Session exists in the page that requires permission control to determine whether the user has the permission to access the page.
The following is a simple example of using Session to implement permission control:
- Login page (login.php)
<?php session_start(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { // 验证登录 $username = $_POST['username']; $password = $_POST['password']; if ($username == 'admin' && $password == '1234') { // 登录成功,保存用户信息到Session $_SESSION['user'] = array( 'username' => $username, 'role' => 'admin' // 权限角色 ); header('Location: index.php'); exit; } else { // 登录失败 $error = '用户名或密码错误'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <h1 id="登录">登录</h1> <form method="post"> <label>用户名:</label><input type="text" name="username"><br> <label>密码:</label><input type="password" name="password"><br> <input type="submit" value="登录"><br> <?php if (isset($error)) { echo $error; } ?> </form> </body> </html>
- Requires permission control Page (index.php)
<?php session_start(); // 检查Session是否存在,判断用户是否登录 if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; } // 检查用户角色,判断用户是否有权限访问该页面 if ($_SESSION['user']['role'] != 'admin') { header('Location: unauthorized.php'); exit; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1 id="欢迎您-php-echo-SESSION-user-username">欢迎您,<?php echo $_SESSION['user']['username']; ?></h1> <p>这是管理员页面,只有管理员才能访问。</p> <a href="logout.php">退出登录</a> </body> </html>
- Exit the login page (logout.php)
<?php session_start(); // 销毁Session,用户退出登录 session_destroy(); header('Location: login.php'); exit; ?>
2. Use the database to implement permission control
In the example of using Session to implement permission control, user information is stored in Session. If the web application has multiple servers at the same time, the sharing of Session information may cause problems. At this time, we can save user information in the database to achieve permission control in a distributed environment.
The following is a simple example of using a MySQL database to implement permission control:
- Create user table
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `role` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- User login processing (login. php)
<?php session_start(); $user = null; if ($_SERVER['REQUEST_METHOD'] == 'POST') { // 验证登录 $username = $_POST['username']; $password = $_POST['password']; // 查询用户信息 $con = mysqli_connect('localhost', 'root', '', 'test'); $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'"; $result = mysqli_query($con, $sql); $user = mysqli_fetch_assoc($result); mysqli_close($con); // 验证用户信息,保存用户信息到Session if ($user != null) { $_SESSION['user'] = $user; header('Location: index.php'); exit; } else { // 登录失败 $error = '用户名或密码错误'; } } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <h1 id="登录">登录</h1> <form method="post"> <label>用户名:</label><input type="text" name="username"><br> <label>密码:</label><input type="password" name="password"><br> <input type="submit" value="登录"><br> <?php if (isset($error)) { echo $error; } ?> </form> </body> </html>
- Page that requires permission control (index.php)
<?php session_start(); // 检查Session是否存在,判断用户是否登录 if (!isset($_SESSION['user'])) { header('Location: login.php'); exit; } // 检查用户角色,判断用户是否有权限访问该页面 if ($_SESSION['user']['role'] != 'admin') { header('Location: unauthorized.php'); exit; } ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h1 id="欢迎您-php-echo-SESSION-user-username">欢迎您,<?php echo $_SESSION['user']['username']; ?></h1> <p>这是管理员页面,只有管理员才能访问。</p> <a href="logout.php">退出登录</a> </body> </html>
- Logout page (logout.php)
<?php session_start(); // 销毁Session,用户退出登录 session_destroy(); header('Location: login.php'); exit; ?>
Summary:
This article introduces how to implement permission control using Session and database. Permission control implemented using Session is simple and suitable for small Web applications; permission control implemented using database is more flexible and more suitable for large Web applications. No matter which method is used, the key is to understand the principles and implementation methods of permission control to ensure the security and stability of web applications.
The above is the detailed content of How to use PHP to implement permission control functions. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

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

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.

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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 Chinese version
Chinese version, very easy to use

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Atom editor mac version download
The most popular open source editor
