I have a user login system for a website set up with PHP and MySQL. My question was whether or not I could modify what I have now, to create a “permissions” system. In other words, only display certain controls for users and different ones for administrators. In my mysql table I have columns 'id', 'username', 'password', and an ENUM ‘permissions’ with ‘a’,’b’. ‘a’ is default (not admin). Below I will show you what I have tried.
This file is “checklogin.php” (for the sake of saving space I will not add all of the code)
//First I include variables to connect to the database & connect
//Then I define username and password as $_POST from a form on an earlier page
$user=a;
$admin=b;
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword' and permissions='$user'";
$sqladmin="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword' and permissions='$admin'";
$result=mysql_query($sql);
$resultadmin=mysql_query($sqladmin);
$count=mysql_num_rows($result);
$countadmin=mysql_num_rows($resultadmin);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
session_register("user");
header("location:login_success.php");
}
else {
if($countadmin==1){
session_register("myusername");
session_register("mypassword");
session_register("admin");
header("location:login_success.php");
}
else {
if($count==0) {
if($countadmin==0) {
echo "Wrong Username or Password";
}
}
}
}
So in this file I am checking how many rows of the table match the user input and whether or not it is admin, and if there is one, then I register a session with username, password, and permissions.
Next, I have the file “login_success.php“
<?php
session_start();
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
else {
}
?>
<html>
<body>
Login Successful
<?php
if(session_is_registered(admin)){
echo "Welcome Admin!";
}
else {
echo "Not admin...";
}
?>
The code above simply checks if the session is registered and if not, sends you back to the login form. Below that is a section of code that checks if the user is an admin.
The login part of this works I just can’t work out the permissions.
So finally, I guess my question is why does this not work? It seems logically correct. Sorry for the lengthy post. Thanks for any help.
I would suggest you the logic as follows: if a user has “a” in one of his columns, then you treat him differently. That means that still one only row is coming up for every user. One only session. Same data strusture. Same session. But basing on what is the value of, say, column “permissions” you open him more “doors” in your application. Where everything you gonna have to do is to check if the “permission” of his session is set to “a” or whatever identifies him as admin.
Hope this helps.
maxim