I already have a login system ready and 100% working, but now I would like to add access levels when logging in and I have no idea how. In my database, in the table of my logins, there is a column that I created called ‘permission_level’ and the default is set to ‘default’, and the administrators as ‘master’
How can I solve this?
Unsuccessful attempt:
<?php $mysqli = new mysqli('', '', '', ''); if (mysqli_connect_errno()) { printf("Connect failed: %sn", mysqli_connect_error()); exit(); } $query = "SELECT permission_level FROM authme WHERE = '".$user."'"; echo $user; if ($result = $mysqli->query($query)) { /* fetch associative array */ while ($row = $result->fetch_assoc()) { printf ("%s n", $row["permission_level"]); } /* free result set */ $result->close(); } session_start(); $_SESSION['UserSession'] = $_POST['username'];
Advertisement
Answer
You need to store the db table data to the session variable after the sql query.
(1) Please move session_start(); to the start of the page.
(2) and then Change
if ($result = $mysqli->query($query)) { /* fetch associative array */ while ($row = $result->fetch_assoc()) { printf ("%s n", $row["permission_level"]); } /* free result set */ $result->close(); }
to
if ($result = $mysqli->query($query)) { /* fetch associative array */ while ($row = $result->fetch_assoc()) { $_SESSION['permission_level'] = $_row['permission_level']; printf ("%s n", $row["permission_level"]); } /* free result set */ $result->close(); }
then you can use $_SESSION[‘permission_level’] to do what you want (remember to put session_start() at the start of all the PHP scripts using the session variable)
For example, if you only want users with permisson level = “master” to access a certain page (e.g. admin.php) , then in this admin.php, you should add, at the top of the script, the following:
<?php session_start(); if ($_SESSION['permission_level']!="master") { echo "You are not allowed to access this page"; exit(); } // add other codes below this line. ?>
On the other hand, as @esquw has mentioned, please also use parameterized prepared statement to avoid SQL injection.