Jump to content

PHP/MySQL user authentication, access levels for certain pages


sleepyw
 Share

Recommended Posts

I have a small site where certain pages require a login. I have that working just fine. Problem is certain protected pages require different types of access.

 

For example, on page 1, you need access level A, B, or C.  On page 2, you need access level C only.  On page 3, you need A or B only, etc.

 

I snagged some code online that works for user auth, but there's no way I can see to add permissions to it, plus it seems to use some outdated (non-preferred code).

 

I'm still new to PHP and a lot of code I find online is very complex and technical and does more than I need it to. I just need simple login, using a MySQL table to add usernames, passwords, and access levels.

 

Here's a snippet of code I'm currently using:

 

Password protected pages have this:

 

<?
session_start():

if(!session_is_registered("username")){
header("location:_login.php");
}

 

Then on the _login.php page, which includes the form to login, it looks like:

 

<?
// Use session variable on this page. This function must put on the top of page.
session_start();

////// Logout Section. Delete all session variable.
session_destroy();

$message="";

////// Login Section.
$Login=$_POST['Login'];
if($Login){ // If clicked on Login button.
$username=$_POST['username'];
$md5_password=md5($_POST['password']); // Encrypt password with md5() function.

// Connect database.
$host="localhost"; // Host name.
$db_user=""; // MySQL username.
$db_password=""; // MySQL password.
$database="tutorial"; // Database name.
mysql_connect($host,$db_user,$db_password);
mysql_select_db($database);

// Check matching of username and password.
$result=mysql_query("select * from admin where username='$username' and password='$md5_password'");
if(mysql_num_rows($result)!='0'){ // If match.
session_register("username"); // Craete session username.
header("location:main.php"); // Re-direct to main.php
exit;
}else{ // If not match.
$message="--- Incorrect Username or Password ---";
}

} // End Login authorize check.
?>

 

It looks like it's the protected page that needs some kind of access level check added below session_start. The way this is wokring is once someone is logged in, they can access any of the "protected" pages. I have a db field in the username/password table called "access" that has different levels.  Is there a way to apply those levels to the protected pages?

Link to comment
Share on other sites

I'd recommend using numbers instead of letters, but that's more personal preference than anything. For your checks you can use "$value > 5" etc.

 

Anyway, where you have this:

<?php
if(!session_is_registered("username")){
header("location:_login.php");
}
?>

 

You would just want to add some additional checks, probably to the database to run a query. Like this:

<?php
if(!session_is_registered("username")){
///MySQL Connection Goes Here
$result = mysql_query("SELECT permission FROM users WHERE username = '" . $_SESSION['username'] . "' LIMIT 1") or die(mysql_error());
$permission = mysql_fetch_array($result);
if ($permission == "A")
{
header("location:_login.php");
} else {
echo 'Not high enough permissions.';
}
}
?>

Link to comment
Share on other sites

create a database field for accesslevel or usertype

 

use that in ur SQL statements in the where clause.

 

Sth like WHERE username  = $username AND password = $password AND Usertype = 1 or 2 or 3/a or b or c(whatever you used)

 

Then make sure there is a seesion you created which you parse to the Usertyep/Access level variablee so you can use that to check on every page as a check.

 

Link to comment
Share on other sites

The way I gave does have the user levels/permissions stored in the database. Each page is different and will require some amount of static context. Additionally you could store the page names in the database with the proper userlevels and then run a function that checks the current page and checks the database for the user levels that the user must meet.

Link to comment
Share on other sites

Actually, the code I pasted above was before I added the WHERE clause with permissions. The problem is that only works the first time a user accesses the page. Then, once they're logged in, they can get to any protected page, even if their access doesn't permit it because the  code on the protected page only checks to see if the user is logged in. It doesn't check their permission level. That's what I need help with.

Link to comment
Share on other sites

I'd recommend using numbers instead of letters, but that's more personal preference than anything.

I actually have words and abbreviations (like "Admin", "Master", etc.) instead of letters. I used letters above as an example. Each level is not all encompassing. In other words, if someone is a level 1, that doesn't mean that level 2 people can also access all level 1 areas. They are independent of each other, as different access levels need to get to different areas, bot not each others. Sometimes there are cases where 2 different access levels need to get to the same area, in which case I'd need to use an OR statement when listing which access levels can get to that page.

 

With the code you wrote, it seems like if the user already logged in from another page, it's not even going to check their permissions.  Does there need to be an IF/ELSE statement - the first saying if the user IS logged in, and the ELSE to redirect them to the login page?

Link to comment
Share on other sites

OK - here's what I did and all this seems to do is redirect me to the users_login.php page regardless.

 

users.php:

<?php
session_start(); 

if(!session_is_registered("username")){ 
header("location:users_login.php"); 
}

if(session_is_registered("username")){

//MySQL db connection info here

$result = mysql_query("SELECT access FROM Users WHERE username = '" . $_SESSION['username'] . "' LIMIT 1") or die(mysql_error());
$permission = mysql_fetch_array($result);
if ($permission != "ADMIN" OR "ALL")
{
header("location:users_login.php");
} 
}

?>

 

 

The users_login.php code looks like this:

<?php
session_start();

$message="";

// Login Section
$Login=$_POST['Login'];
if($Login){ // If clicked on Login button
$username=$_POST['username'];
$md5_password=md5($_POST['password']); // Encrypt password with md5() function

// MySQL connection goes here....

// Check matching of username and password
$result=mysql_query("SELECT * from Users WHERE username='$username' AND password='$md5_password' AND access='ALL' OR access='ADMIN'");
if(mysql_num_rows($result)!='0'){ // If match
session_register("username"); // Create session username
header("location:users.php"); // Re-direct to users.php
exit;
}else{ // If not match
$message="<div style='position:absolute; left:325px; top:50px; width:600px; height:auto; z-index:4;'>Your username and password do not match, or you do not have permission to access this page.</div>";
}

} // End Login authorize check
?>

 

So the users_login.php code seems fine - it's the new permissions checking code on the users.php page that seems off.

Link to comment
Share on other sites

Sorry, I failed you, try this in users.php (Note the array index in the if check)

<?php
$permission = mysql_fetch_array($result);
if (($permission[0] != "ADMIN") || ($permission[0] != "ALL"))
?>

 

EDIT: Fixed the If statement furthur.

Link to comment
Share on other sites

This is where my n00bness comes in. I don't know what I should be doing regarding the index [0].  Left as-is, that new if statement has the same result as before.

 

BTW - I appreciate your help. Seems like this code should work, but I'm stuck in a login loop. I did verify that the username I'm using to test this does have ADMIN rights. I also know it should work because the IF statement on the users_login.php page works correctly.

 

Here's my updated code for users.php:

 

<?php
session_start(); 

if(!session_is_registered("username")){ 
header("location:users_login.php"); 
}

//MySQL connection

$result = mysql_query("SELECT access FROM Users WHERE username = '" . $_SESSION['username'] . "' LIMIT 1") or die(mysql_error());
$permission = mysql_fetch_array($result);
if (($permission[0] != "ADMIN") || ($permission[0] != "ALL"))
{
header("location:users_login.php");
} 

?>

Link to comment
Share on other sites

Just for debugging, try this and see what is output:

<?php
if (($permission[0] != "ADMIN") || ($permission[0] != "ALL"))
{
// header("location:users_login.php");
echo 'Success: <br /><pre>';
print_r($permission);
echo '</pre>';
} else {
echo 'Failure: <br /><pre>';
print_r($permission);
echo '</pre>';
?>

Link to comment
Share on other sites

Success:

 

Array

(

    [0] => ADMIN

    [access] => ADMIN

)

 

 

 

When I log in from an account without admin or all permissions, I get this:

 

Success:

 

Array

(

    [0] => DSR

    [access] => DSR

)

 

 

 

I presume the first one should have said Failure, since I WAS logged in with Admin permissions.

Link to comment
Share on other sites

Okay, on the right track, it was a logic issue. You want people to login ONLY if they aren't marked ADMIN or marked ALL. My fix was off. Change the conditional If statement to:

 

if ((trim($permission[0]) != "ADMIN") && (trim($permission[0]) != "ALL"))

 

And that should solve the problem. I also added the trim to make sure it doesn't fail because of a white space.

Link to comment
Share on other sites

You da freakin' man!

 

Thank you so much. Works like a charm!

 

EDIT: Problem....if i don't have permissions, I get redirected to the users_login.php page, and no matter what I enter there, it won't let me in.

 

EDIT 2: Could it have to do with the original username still being stored in the session and it can't overwrite it without clearing the session? Perhaps the workaround is not to let the user try to log in again from that page and just say permission denied. Hmmmm...

Link to comment
Share on other sites

What I do is ....

 

Grab the data when user logins. Serialize the information I want to hold in my session.

 

$userinfo = $row['userid'].','.$row['privs'];
$_SESSION['user'] = base64_encode(serialize($userinfo));

 

If you are using a header or template system you would then just unserialize the session and define variables with the values...

 

Example:

// Fetch User Information
$member = unserialize(base64_decode($_SESSION['user']));
$mdata = explode(',',$member);
// Assign User Info
define ("USERID",$mdata[0]);
define ("PRIVS",$mdata[1]);

 

Now on any of your pages you can do :

// Check User Permissions
if (PRIVS < "3") { // Check to see if user is LEVEL 3 or higher
@header("Location:index.php?p=denied");// Send them to denied page
die("<script>window.location='index.php?p=denied';</script>"); //js redirect backup
}

 

 

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.