管理不同的用户组以查看页面

In my application, there are different group of users such as student, teacher, admin, principal etc., can log in to my application. And i'm having a php such as students_add.php which is a student manager, so only admin can view that page.

Now i've to set the file "students_add.php" can be accessed only by admin. For that, i can create a session variable like $_SESSION['user_type'] = 'A' then, by checking the session variable while the users get log in to my app, i can re-direct or set 404 error by using header() and .htaccess. But i don't want to use this checking mechanism for each and every file in my app.

So, i want a simple solution to resolve my problem, and also please let me know what are the methods/logic out there to control a page being accessed by different user-group in PHP.

You basically have to check in every script, as there's no other way. The only way is how you do that. The best approach is to move the checking code into separated script and then simply include it at the begining of every other script with

require_once('my_checking_script.php`);

This is most clean approach. Alternatively, if you got really, really high number of scripts, you can use php.ini's auto_prepend_file directive.

There isnt a magic trick.

admin.php

if(not admin) logout
...

user.php

if(not user or admin) logout
...

I'm pretty sure you have to check user credentials every time they need to be checked. Maybe OOP can take some pain out of the repeating yourself but nevertheless, you need to somehow differentiate the user groups and their access rights every time users do something.

I currently use numerical user levels when managing user group rights. Larger the number, more rights user has. So can have different kind of code blocks inside a single file (or different kind of files that only some users can access). A simple example:

<?php
if ($user_level >= 1){
  //this is allowed fo basic users (and of course advanced users)

  if ($user_level >= 5){
    //this is allowed for advanced users (i.e. principal) but not basic users
  }

  //and again, this is allowed fo basic users (and of course advanced users)
}
?>

In addition to one user_level you can of course have special attributes like is_admin etc. But you always have to write it down. When was the last time computers/programs did anything you wanted them to do without you (or someone else) having first had the trouble of programming the allowed actions (and the restrictions)?