Jump to content

How to make a multiple user level in PHP ?


jayart
 Share

Recommended Posts

 

define('USER_LEVEL_TEACHER', 1);
define('USER_LEVEL_STUDENT', 2);
define('USER_LEVEL_CASHIER', 4);
define('USER_LEVEL_ADMIN', ;

if ($userLevel & USER_LEVEL_ADMIN) {
  // admin
}

 

but how? i mean i need to redirect different page.. im new in php :) please can you explain? Edited by ignace
Link to comment
Share on other sites

sorry, i have code for this but i have an error with "Notice: Undefined index: position in C:\xampp\htdocs\svbm_ernolment_system\login.php on line 20"

 

HERES THE CODE: 

 

<?php
//Start session
session_start();
 
//Connect to mysql server
include('connect.php');
 
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
 
//Sanitize the POST values
$login = clean($_POST['id']);
$password = clean($_POST['password']);
$position = clean($_POST['position']);
$result = mysql_query("SELECT * FROM user WHERE idnumber='$login' AND password='$password'");
while($row = mysql_fetch_array($result))
{
$position = $row['position'];
}
if ($position=='admin')
{
//Create query
$qry="SELECT * FROM admin WHERE idnum='$login' AND password='$password'";
$result=mysql_query($qry);
//while($row = mysql_fetch_array($result))
//  {
//  $level=$row['position'];
//  }
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
session_write_close();
//if ($level="admin"){
header("location: admin/index.php");
exit();
}else {
//Login failed
header("location: loginform.php");
exit();
}
}else {
die("Query failed");
}
}
 
$result = mysql_query("SELECT * FROM user WHERE idnumber='$login' AND password='$password'");
while($row = mysql_fetch_array($result))
{
$position = $row['position'];
}
if ($position=='student')
{
//Create query
$qry="SELECT * FROM prereg WHERE idnumber='$login' AND password='$password'";
$result=mysql_query($qry);
//while($row = mysql_fetch_array($result))
//  {
//  $level=$row['position'];
//  }
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['SESS_FIRST_NAME'] = $member['idnumber'];
session_write_close();
//if ($level="admin"){
header("location: student/profile.php");
exit();
}else {
//Login failed
header("location: loginform.php");
exit();
}
}else {
die("Query failed");
}
}
if ($position=='Casher')
{
//Create query
$qry="SELECT * FROM casher WHERE idnumber='$login' AND password='$password'";
$result=mysql_query($qry);
//while($row = mysql_fetch_array($result))
//  {
//  $level=$row['position'];
//  }
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['SESS_FIRST_NAME'] = $member['idnumber'];
session_write_close();
//if ($level="admin"){
header("location: casher/index.php");
exit();
}else {
//Login failed
header("location: loginform.php");
exit();
}
}else {
die("Query failed");
}
}
if ($position=='teacher')
{
//Create query
$qry="SELECT * FROM teacher WHERE idnumber='$login' AND password='$password'";
$result=mysql_query($qry);
//while($row = mysql_fetch_array($result))
//  {
//  $level=$row['position'];
//  }
//Check whether the query was successful or not
if($result) {
if(mysql_num_rows($result) > 0) {
//Login Successful
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['SESS_FIRST_NAME'] = $member['idnumber'];
session_write_close();
//if ($level="admin"){
header("location: teacher/index.php");
exit();
}else {
//Login failed
header("location: loginform.php");
exit();
}
}else {
die("Query failed");
}
}
 
?>
Link to comment
Share on other sites

Your design has some flaws in it. First of all, mysql extension is deprecated, use mysqli or PDO. Second, for a system like this Id prefer object oriented approach as you are not handling a personal home page type of website. I dont get the entire picture of what your site is supposed to do, but below is a sample code that will help(note it is not a complete design, you can do some refactoring to make it better, its used for illustrative purposes only):

abstract class User{
   
    public function __construct(UserDTO $userDTO){
        $this->id = $userDTO->idnumber;
        $this->idNumber = $userDTO->idnumber;
        $this->password = $userDTO->password; // Assume you already did password hashing/salting beforehand
        $this->position = $userDTO->position;
        // Whatever additional fields
    }

    abstract public function redirect();
}

class Admin extends User{
    public function redirect(){
        header('Location: admin.php');
    }
}

class Teacher extends User{
    public function redirect(){
        header('Location: teacher.php');
    }
}

class Student extends User{
    public function redirect(){
        header('Location: student.php');
    }
}

class Cashier extends User{
    public function redirect(){
        header('Location: admin.php');
    }
}

class UserFactory{
    
    public function __construct(UserDTO $userDTO){
        $this->userDTO = $userDTO;
    } 
   
    public function createUser(){
        $method = "create{$userDTO->position}";
        $this->$method();
    }

    private function createStudent(){
        return new Student($this->userDTO);
    }

    private function createTeacher(){
        return new Teacher($this->userDTO);
    }

    private function createAdmin(){
        return new Admin($this->userDTO);
    }

    private function createCashier(){
        return new Cashier($this->userDTO);
    }
}

// Assume you have a PDO object available, but not a data mapper(for a small system). 
$PDO = new PDO(/*.. Your DB credentials..*/);
$stmt = PDO->prepare(/*.. Your SQL ..*/);
$stmt->execute();
$userDTO = $pdo->fetchObject("UserDTO"); //UserDTO, a data transfer object

$factory = new UserFactory($userDTO);
$user = factory->createUser();
$user->redirect();
exit();

This design is better 'cause you can use polymorphism to eliminate unnecessary conditionals. The advantage is more evident once you have to write duplicate if...else statement to check user level/position in other script/class files. Also once your site grows, there is a good chance that you will have other actions beyond redirection that will require checking the user level/position conditionals. All you have to do then is to add such method for each User sub-classes. As you see, with Polymorphism, you dont need to worry about writing these conditionals over and over again, PHP will do it for you. Note the design can be further improved using a domain model - data mapper design pattern, you will learn this later once you become more familiar with PHP and OOP.

Edited by Hall of Famer
Link to comment
Share on other sites

@Hall of Famer: You are constantly advocating good OO design, yet here you tie your application layer to your model.. A user should not be concerned about how an application handles login or about where a user should go after login.

 

I said it was just for illustrative purposes, if you earnestly believe this is what I will end up having in my own OO architecture you'd be serious mistaken. In my OO design Id completely separate the domain layer from application layer, the domain model will not know how to handle redirection, login and this kind of behavior. The controller will call login based on the subclass of model, but then you need to create a class hierachy for controllers first, maybe service layers too if you need further separation of concerns. Also I wont use PDO to fetch objects in the application layer either, instead I will use a data mapper. Now you see it will require significant overhead, and thus inappropriate in a single post like this to explain.

 

Yeah I will do it if it were my own application, but here I just want to explain the concept of polymorphism, more precisely how to use polymorphism to eliminate conditionals. Nothing more nothing less, I dont wish to write 20+ classes/interfaces to scare the OP away, perhaps this forum wont allow me to post/upload all the source code of these classes anyway since they will be too long. Like I said, you can always refactor after design the first draft of your system architecture, for OP's skillset the above code should suffice, once he learns more about OOA/OOD he will move on to more advanced OOP.

Edited by Hall of Famer
Link to comment
Share on other sites

Your design has some flaws in it. First of all, mysql extension is deprecated, use mysqli or PDO. Second, for a system like this Id prefer object oriented approach as you are not handling a personal home page type of website. I dont get the entire picture of what your site is supposed to do, but below is a sample code that will help(note it is not a complete design, you can do some refactoring to make it better, its used for illustrative purposes only):

abstract class User{
   
    public function __construct(UserDTO $userDTO){
        $this->id = $userDTO->idnumber;
        $this->idNumber = $userDTO->idnumber;
        $this->password = $userDTO->password; // Assume you already did password hashing/salting beforehand
        $this->position = $userDTO->position;
        // Whatever additional fields
    }

    abstract public function redirect();
}

class Admin extends User{
    public function redirect(){
        header('Location: admin.php');
    }
}

class Teacher extends User{
    public function redirect(){
        header('Location: teacher.php');
    }
}

class Student extends User{
    public function redirect(){
        header('Location: student.php');
    }
}

class Cashier extends User{
    public function redirect(){
        header('Location: admin.php');
    }
}

class UserFactory{
    
    public function __construct(UserDTO $userDTO){
        $this->userDTO = $userDTO;
    } 
   
    public function createUser(){
        $method = "create{$userDTO->position}";
        $this->$method();
    }

    private function createStudent(){
        return new Student($this->userDTO);
    }

    private function createTeacher(){
        return new Teacher($this->userDTO);
    }

    private function createAdmin(){
        return new Admin($this->userDTO);
    }

    private function createCashier(){
        return new Cashier($this->userDTO);
    }
}

// Assume you have a PDO object available, but not a data mapper(for a small system). 
$PDO = new PDO(/*.. Your DB credentials..*/);
$stmt = PDO->prepare(/*.. Your SQL ..*/);
$stmt->execute();
$userDTO = $pdo->fetchObject("UserDTO"); //UserDTO, a data transfer object

$factory = new UserFactory($userDTO);
$user = factory->createUser();
$user->redirect();
exit();

This design is better 'cause you can use polymorphism to eliminate unnecessary conditionals. The advantage is more evident once you have to write duplicate if...else statement to check user level/position in other script/class files. Also once your site grows, there is a good chance that you will have other actions beyond redirection that will require checking the user level/position conditionals. All you have to do then is to add such method for each User sub-classes. As you see, with Polymorphism, you dont need to worry about writing these conditionals over and over again, PHP will do it for you. Note the design can be further improved using a domain model - data mapper design pattern, you will learn this later once you become more familiar with PHP and OOP.

BTW thanks for helping.. idk how to use mysqli or PDO as new in php :) my system is online enrollment system . and i dont know how to apply this code to my code..

Link to comment
Share on other sites

I said it was just for illustrative purposes, if you earnestly believe this is what I will end up having in my own OO architecture you'd be serious mistaken.

So you are purposefully pointing the OP to bad practices? Don't be overly defensive, ignace is just trying to help.

I don't think it's the best idea to point a new programmer to OO right away, he probably has no idea what he is looking at in your example.

 

However, OP, trq has pointed you to a good authorization interface that I can think you can manage to implement if you go through the documentation.

Link to comment
Share on other sites

So you are purposefully pointing the OP to bad practices? Don't be overly defensive, ignace is just trying to help.

I don't think it's the best idea to point a new programmer to OO right away, he probably has no idea what he is looking at in your example.

 

Nope I am not being overly defensive, I do in fact know what I am doing, and in fact if you read Ignace's post history with me you will know why I am talking about this. There was a time when I brough up that PHP's namespace is lacking wildcard import by using a draft user class hierachy example to illustrate how importing multiple classes can be made easier, and Ignace went on to comment on how the user class hierachy is flawed. Dont you think this is completely missing the point of dicussion?

Edited by Hall of Famer
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.