Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Controlling User Access in PHP

, 8 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
How to control user access in PHP.

At a given point, your application will need to handle user access, and controlling each specific user to specific content. The most common example that we will encounter will be regular users and administrative users. Regular users should only see content that is relevant to them. An admin user in many cases will be able to view all users, sensitive information that if in the wrong hands, could cause damage to the website. There are many ways to have a simple website, that has a regular user panel, and an admin panel. From my previous post of Saving Records to database, let’s take the same table we created for users, and add a field called USERS_ROLE with datatype of ENUM, and values of admin, user.

Create Users Table

CREATE TABLE users(
        users_id int(11) NOT NULL auto_increment,
        users_fname VARCHAR(60),
        users_lname VARCHAR(60),
        users_email VARCHAR(60),
        users_pass VARCHAR(32),
        users_role ENUM('admin', 'user'),
        PRIMARY KEY (users_id)
    );

Now with this new field in the database, we can determine what type of user is actually accessing our website. I have found that the best way to determine the type of user is to add this same field to our sessions variable once we login. If you have yet to figure out how to log in a user, then take a look over to that tutorial here: http://www.jotorres.com/2012/04/php-mysql-login-form/.

Let’s do a some changes to our ‘validate_login.php’ file, adding a user session. That way, the user can browse throughout the website without being asked to be authenticated. The first thing we must do is start a session. After starting the session, we validate the user credentials. Once the credentials have been verified, we go ahead and create a sessions variable. This variable will contain unique information for that particular user, including the role that has been assigned to that user. So instead of echoing out that the login was successful, we write some logic for our needs. Let’s take a look:

validate_login.php

<?php
session_start();
// Grab User submitted information
$email = $_POST["users_email"];
$pass = $_POST["users_pass"];

// Connect to the database
$con = mysql_connect("localhost","root","");
// Make sure we connected succesfully
if(! $con)
{
    die('Connection Failed'.mysql_error());
}

// Select the database to use
mysql_select_db("my_dbname",$con);

$result = mysql_query("SELECT users_id, users_email, users_role " + 
  "FROM users WHERE users_email = $email AND users_pass = $pass");

$total = mysql_num_rows($result);

$protocol = $_SERVER['HTTPS'] ? "https" : "http";
$url = $protocol.'://'.$_SERVER['HTTP_HOST'];

if($total == 1){
    // Credentials match so we create session variables
    $row = mysql_fetch_assoc($result);
    $_SESSION['users_id'] = $row['users_id'];
    $_SESSION['users_email'] = $row['users_email'];
    $_SESSION['users_role'] = $row['users_role'];
    
    // After assinging the session variables, 
    // set the url to redirect the user to members page.    
    $url .= '/members.php';    
}
else{
    // If not, then redirect the user the login page with an error
    $url .= '/login.php?error=true';
}
header("Location: $url");
exit;

?>

Notice that we redirect the user to the login page if the credentials don’t match. We have also added something to the end of the URL. We just sent a variable error, that can be accessed via the get variable in PHP. This variable is to display to the user if something went wrong with the login process. To display the error to the user, simply ask if the variable is set, and if so, then display an error message, like this:

(withih login.php)

<?php 
if(isset($_GET['error'] && $_GET['error'] == true){
    echo 'Invalid Username and/or Password.';
}
?>

Those previous lines can be added anywhere in your code, and of course, you will put them in a reasonable place. Now, here comes the interesting part. Within the new members page, we would like to display content that is relative to a user. Let’s assume that we have the menus on separate files, of which we will call ‘admin_menu.php’ and ‘users_menu.php’. To determine how which menu to display, we can simply use an if statement, or use a switch statement. For this example, I am going to use the switch statement. Our members page could look something like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
            "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jotorres Memebers Page</title>
</head>
<body>
<h2>Welcome to members page.</h2>
<?php 
    switch($_SESSION['users_role']){
        case 'admin':
            include('admin_menu.php');
            break;
        case 'users':
            include('users_menu.php');
            break;
    }
?>
</body>
</html>

As you can see, with a simple switch, you can handle what you would like to display for different types of users. You will be able to add new menus such as, ‘not_logged_user_menu’.

In summary, you can see how easy it is to handle user roles within a website without having to create so many different pages. Remember, for the sake of simplicity, I have not added any sanitation or filters for user inputs. That is solely your responsibility on how you want to handle security in your website.

Hope you enjoyed reading this!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

jotorres
Software Developer
Puerto Rico Puerto Rico
As a computer scientist, I strive to learn more everyday in my field. Everything I learn, I share with my community by writing articles for future references.
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 3 PinmemberCarlos Luis8-Oct-12 13:40 
You should not store passwords in plain text as you do here.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411023.1 | Last Updated 8 Oct 2012
Article Copyright 2012 by jotorres
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid