将用户从 username 到 user_group [英] Maching users from username to user_group

查看:43
本文介绍了将用户从 username 到 user_group的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在我的网站上建立了一个排名系统.(可能有更简单的方法来做到这一点)这是我尝试过的.

So im setting up a ranks system on my website. (there is probably an easier way to do it) Here is what i tried.

<?php include('../core/db/server.php');

//get users group
$query = "SELECT user_group FROM users";
$result = $db->query($query);

if (isset($_SESSION['username'])) {
    if ($username['user_group'] == 'owner') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $owner;
        header('location: home.php');
    }

    if ($username['user_group'] == 'admin') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $admin;
        header('location: home.php');
    }

    if ($username['user_group'] == 'mod') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $mod;
        header('location: home.php');
    }

    if ($username['user_group'] == 'dev') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $dev;
        header('location: home.php');
    }

    if ($username['user_group'] == 'helper') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $helper;
        header('location: home.php');
    }

    if ($username['user_group'] == 'builder') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $builder;
        header('location: home.php');
    }

    if ($username['user_group'] == 'member') {
        $_SESSION['user'] = $logged_in_user;
        $_SESSION['success'] = "You are now logged in";
        $_SESSION['loggedin'] = "logggedin session";
        $_SESSION['panel'] = $member;
        header('location: home.php');
    }

}

这里是我的 server.php 文件以获取额外信息.(包括详细信息)

and here is my server.php file for extra info. (details included)

<?php
session_start();

// variable declaration
$username = "";
$email    = "";
$errors = array();
$_SESSION['success'] = "";

// connect to database
$db = mysqli_connect('localhost', 'root', '', 'havokcraft');

// REGISTER USER
if (isset($_POST['reg_user'])) {
    // receive all input values from the form
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $email = mysqli_real_escape_string($db, $_POST['email']);
    $password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
    $password_2 = mysqli_real_escape_string($db, $_POST['password_2']);

    // form validation: ensure that the form is correctly filled
    if (empty($username)) { array_push($errors, "Username is required"); }
    if (empty($email)) { array_push($errors, "Email is required"); }
    if (empty($password_1)) { array_push($errors, "Password is required"); }

    if ($password_1 != $password_2) {
        array_push($errors, "The two passwords do not match");
    }

    // register user if there are no errors in the form
    if (count($errors) == 0) {
        $password = md5($password_1);//encrypt the password before saving in the database
        $query = "INSERT INTO users (username, email, password, user_group)
                  VALUES('$username', '$email', '$password', 'member')";
        mysqli_query($db, $query);

        $_SESSION['username'] = $username;
        $_SESSION['user_group'] = $usergroup;
        $_SESSION['success'] = "You are now logged in";
        header('location: index.php');
    }

}

// ...

// LOGIN USER
if (isset($_POST['login_user'])) {
    $username = mysqli_real_escape_string($db, $_POST['username']);
    $password = mysqli_real_escape_string($db, $_POST['password']);

    if (empty($username)) {
        array_push($errors, "Username is required");
    }
    if (empty($password)) {
        array_push($errors, "Password is required");
    }

    if (count($errors) == 0) {
        $password = SHA1($password);
        $query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
        $results = mysqli_query($db, $query);

        if (mysqli_num_rows($results) == 1) {
            $_SESSION['username'] = $username;
            $_SESSION['user_group'] = $usergroup;
            $_SESSION['success'] = "You are now logged in";
            header('location: index.php');
        }else {
            array_push($errors, "Wrong username/password combination");
        }
    }
}

基本上,我想将某些会话设置为某些组,这是我可以向已登录/已注销或没有足够高排名访问页面的用户隐藏链接的唯一方法.

Basically i want to set certain sessions to certain groups, its the only way i can hide links from users that are either logged in/logged out or don't have a high enough rank to visit a page.

推荐答案

如何制作一个简单的用户注册和登录表单?

在制作用户注册门户时,您首先应该考虑的是您将在何处以及如何存储用户帐户.为此,我们将使用带有下表的 MySQL 数据库:

How to make a simple user registration and log in form?

The first thing you should consider when making user registration portal is where and how you are going to store user accounts. For this purpose we are going to use MySQL database with the following table:

CREATE TABLE IF NOT EXISTS `accounts` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `Username` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `Hash` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `UserType` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

在这个表中,我们将存储用户名和密码哈希.我们还有一个列会告诉我们帐户的类型;无论是普通用户还是管理员.

In this table we are going to store the username and the password hash. We also have a column that will tell us the type of the account; whether it is a normal user or an admin.

我们显然需要连接到数据库并启动会话.这些主题超出了本答案的范围.我们将使用 PDO 连接到保存新表的数据库.

We obviously need to connect to the database and start a session. These topic are out of scope of this answer. We are going to use PDO to connect to our database which holds our new table.

<?php

session_start();

$pdo = new PDO('mysql:host=localhost;charset=utf8mb4;dbname=test', 'dbuser', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

有关 PDO 工作原理的更深入解释,请查看这篇文章:https://phpdelusions.net/pdo

For a more in-depth explanation of how PDO works take a look at this article: https://phpdelusions.net/pdo

我们现在可以创建一个简单的函数来在数据库中注册一个用户.该函数将接受 3 个参数:数据库连接、用户名和密码.

We can now create a simple function that will register a user in the database. This function will accept 3 parameters: the DB connection, username, and password.

此函数将创建密码的哈希值,然后丢弃此密码.这是一个简单的例子,但在现实世界中,您可能希望添加更多检查并使其更加万无一失.

This function will create a hash of the password, then discard this password. It is a simple example, but in real-word you would probably want to add more checks and make this more foolproof.

function register(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
     
    $stmt = $db->prepare('INSERT INTO accounts(Username, Hash, UserType) VALUES(?,?,?)');
    $stmt->execute([
        $username,
        $hash,
        'user' // or admin
    ]);
}

登录功能

就像我们对注册函数所做的那样,我们将创建一个用于登录的函数.该函数将接受相同的参数,但它会SELECT 而不是INSERT根据匹配的用户名从数据库中提取.

The login function

Just as we did with the registration function, we will create one function for logging in. The function will accept the same parameters, but instead of INSERT it will SELECT from the database based on the matching username.

如果数据库中有匹配的记录并且根据存储的哈希值验证了密码,那么我们将用户信息存储在会话中.会话将在硬盘驱动器上保留此信息,并为用户提供一个 cookie,以供将来提出请求时使用.使用该 cookie PHP 将在每次请求页面时打开相同的会话.

If there is a matching record in the database and the password is verified against the stored hash then we store the user information in a session. The session will persist this information on the hard drive and it will give the user a cookie to be used when making future requests. Using that cookie PHP will open the same session each time the page is requested.

function login(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
     
    $stmt = $db->prepare('SELECT Id, Hash, UserType FROM accounts WHERE Username=?');
    $stmt->execute([ $username ]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['Hash'])) {
        throw new Exception('Username or password incorrect!');
    }

    $_SESSION['loggedUserId'] = $user['Id'];
    $_SESSION['UserType'] = $user['UserType'];
}

完整代码

我们现在可以将所有这些连接在一起并添加一些 HTML 表单.HTML 部分超出范围,但您希望将其与 PHP 逻辑分开.可能完全放在一个单独的文件中.

The full code

We can now connect all of this together and add some HTML forms. The HTML part is out of scope but you would want to keep it separate from your PHP logic. Probably in a separate file altogether.

<?php

session_start();

$pdo = new PDO('mysql:host=localhost;charset=utf8mb4;dbname=test', 'inet', '5432', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

function register(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
    $hash = password_hash($password, PASSWORD_DEFAULT);
     
    $stmt = $db->prepare('INSERT INTO accounts(Username, Hash, UserType) VALUES(?,?,?)');
    $stmt->execute([
        $username,
        $hash,
        'user' // or admin
    ]);
}

function login(PDO $db, string $username, string $password)
{
    if (!$username || !$password) {
        throw new Exception('Username and password is required!');
    }
     
    $stmt = $db->prepare('SELECT Id, Hash, UserType FROM accounts WHERE Username=?');
    $stmt->execute([ $username ]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['Hash'])) {
        throw new Exception('Username or password incorrect!');
    }

    $_SESSION['loggedUserId'] = $user['Id'];
    $_SESSION['UserType'] = $user['UserType'];
}

if (isset($_POST['register'])) {
    register($pdo, $_POST['username'], $_POST['password']);
}

if (isset($_POST['login'])) {
    login($pdo, $_POST['username'], $_POST['password']);
}

if (!isset($_SESSION['loggedUserId'])):
?>
<!-- Register form -->
<form  method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="register" value="Register">
</form>

<!-- Login form -->
<form  method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" name="login" value="Log in">
</form>
<?php
else:
echo 'Here be something after login. You are a '.$_SESSION['UserType'];
endif;

这是一个非常简单的例子,说明如何在 PHP 中进行注册和登录.我不建议在实时网站上按原样使用它,但出于学习目的,它应该演示此功能的工作原理.

This is a very simple example of how registration and logging in works in PHP. I would not recommend to use it as-is on a live site, but for learning purposes, it should demonstrate how this functionality works.

您可以在此基础上构建并在用户类型不同时执行某些操作.向更多特权用户显示更多内容.

You can build on top of it and do something when the user type is different. Show more content to more privileged users.

这篇关于将用户从 username 到 user_group的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆