Home  >  Article  >  Backend Development  >  How to use PHP to implement permission control functions

How to use PHP to implement permission control functions

PHPz
PHPzOriginal
2023-06-23 10:16:421655browse

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:

  1. 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>登录</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>
  1. 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>欢迎您,<?php echo $_SESSION['user']['username']; ?></h1>
  <p>这是管理员页面,只有管理员才能访问。</p>
  <a href="logout.php">退出登录</a>
</body>
</html>
  1. 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:

  1. 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;
  1. 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>登录</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>
  1. 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>欢迎您,<?php echo $_SESSION['user']['username']; ?></h1>
  <p>这是管理员页面,只有管理员才能访问。</p>
  <a href="logout.php">退出登录</a>
</body>
</html>
  1. 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!

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