0

I am trying to protect some php pages with roles. The code i am using its working when the people make the login but if they know the link and don't make the login they can access the page and i can't understand why.

Can anyone help me?

I am using this code to protect the page where only users with role "admin" can access.

<?php
// Initialize the session
session_start();

// If session variable is not set it will redirect to login page
if(isset($_SESSION['username'])){if ($_SESSION['role']=='admin') {

} else {
  header('location: index.php');
}
}
?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
Osvaldo Cipriano
  • 313
  • 1
  • 2
  • 11
  • **WARNING**: Writing your own access control layer is not easy and there are many opportunities to get it severely wrong. Please, do not write your own authentication system when any modern [development framework](http://codegeekz.com/best-php-frameworks-for-developers/) like [Laravel](http://laravel.com/) comes with a robust [authentication system](https://laravel.com/docs/master/authentication) built-in. At the absolute least follow [recommended security best practices](http://www.phptherightway.com/#security) and **never store passwords as plain-text**. – tadman Dec 11 '17 at 01:40
  • Lets **ALL** use laravel!! not got to learn anything then. – Lawrence Cherone Dec 11 '17 at 01:42
  • Yes Laravel is lot better managing this via Middleware so consider this in your next project or current one also. – Amit Gupta Dec 11 '17 at 01:57
  • I know about Laravel, but i am trying to learn :) – Osvaldo Cipriano Dec 11 '17 at 01:59
  • For core PHP projects, I used to create one extra sub admin table where I used to add columns like orders_access, products_access and store 1 or 0 value in them, that set by admin along with md5 password. – Amit Gupta Dec 11 '17 at 02:02
  • Sub admins used to login with their username and password provided by admin and fetch all the roles admin set for them and pass in session from one common file so that they can access what features assigned to them, at the time of logout unset all privileges. – Amit Gupta Dec 11 '17 at 02:05
  • I hope you will get some idea how to do it. – Amit Gupta Dec 11 '17 at 02:06

1 Answers1

1

Try this:

<?php
    // Initialize the session
    if(!isset($_SESSION)) {
        session_start();
    }

    // If session variable is not set it will redirect to login page
    if(empty($_SESSION['username'])) {
            header('Location: index.php');
    } else {
        if ($_SESSION['role'] != 'admin') {
            header('Location: index.php');
        }
    }
?>