PHP with MySql 多角色用户登录

转载自:http://www.techyari.in/2014/10/multi-user-role-based-login-in-php-with-mysql.html?m=0

Login and logout functionality is crucial to any web application. Today I am going to discuss a role based login system in PHP with MySql database. We will have two login roles. One as admin login and another as user login. When logged in users with admin role will be redirected to admin home page whereas users with user role will be redirected to user home page. I am creating two different pages to make it simple however same strategy can be used to show/hide links based on logged in roles as well.

Download Source Live Demo

User Table Setup

To manage users with both the login roles create a database and setup user table and insert at least two rows. one with admin user role and another with user role.

// setup messages tableCREATE TABLE users(   id INT NOT NULL AUTO_INCREMENT,   username VARCHAR(100) NOT NULL,   password VARCHAR(100) NOT NULL,   role VARCHAR(100) NOT NULL,   PRIMARY KEY (id));

Database Configuration (database-config.php)

Use below code to configure database connection with the database table created in earlier step. Change variable values according to your database environment. 


   // define database related variables   

$database = 'techyari_demos';   $host = 'localhost';   $user = 'root';   $pass = '';   // try to conncet to database   $dbh = new PDO("mysql:dbname={$database};host={$host};port={3306}", $user, $pass);   if(!$dbh){      echo "unable to connect to database";   }   ?>

Login Page (index.php)

Login page contains the login form which points to authenticate.php file when user clicks on login button. In authenticate.php file we receive the user input via $_POST variables and validate the user login credentials.

                      

Log in with your credentials


                                                          

                                $errors = array(                                    1=>"Invalid user name or password, Try again",                                    2=>"Please login to access this area"                                  );                                $error_id = isset($_GET['err']) ? (int)$_GET['err'] : 0;                                if ($error_id == 1) {                                        echo ''.$errors[$error_id].'';                                    }elseif ($error_id == 2) {                                        echo ''.$errors[$error_id].'';                                    }                               ?>  

                                

                                  
                                  
                                  Sign in                                                                    

Authentication (authenticate.php)

This file takes care of authentication, it also requires database-config.php file to connect to database.


require 'database-config.php'; session_start(); $username = ""; $password = "";

if(isset($_POST['username'])){  $username = $_POST['username']; } if (isset($_POST['password'])) {  $password = $_POST['password']; }

$q = 'SELECT * FROM users WHERE username=:username AND password=:password'; $query = $dbh->prepare($q); $query->execute(array(':username' => $username, ':password' => $password)); if($query->rowCount() == 0){  header('Location: index.php?err=1'); }else{  $row = $query->fetch(PDO::FETCH_ASSOC);  session_regenerate_id();  $_SESSION['sess_user_id'] = $row['id'];  $_SESSION['sess_username'] = $row['username'];        $_SESSION['sess_userrole'] = $row['role'];        echo $_SESSION['sess_userrole'];  session_write_close();  if( $_SESSION['sess_userrole'] == "admin"){  header('Location: adminhome.php');  }else{  header('Location: userhome.php');  } 


}?>

Admin Home Page (adminhome.php)

On validation if a user is admin he is redirected to this page. We have included a piece of code on top of the page to check if session exists and the user accessing the page has admin rights. If not the user will be redirected back to login (index) page with proper error messages.


    session_start();    $role = $_SESSION['sess_userrole'];    if(!isset($_SESSION['sess_username']) || $role!="admin"){      header('Location: index.php?err=2');    }?>                Bootstrap 101 Template                        -->

      

      


                                        Toggle navigation                                                        Techyari.in                                      

  •             
  • Logout
  •                                                                          

    This is Admin area.

                                          

                        

    User Home Page (userhome.php)

    This is for normal users, functionality is same as admin page


        session_start();    $role = $_SESSION['sess_userrole'];    if(!isset($_SESSION['sess_username']) || $role!="user"){      header('Location: index.php?err=2');    }?>                Bootstrap 101 Template                        -->

          

          


                                            Toggle navigation                                                        Techyari.in                                      

  •             
  • Logout
  •                                                                          

    This is User area.

                                          

                        

    Session Management (logout.php)

    Session management is crucial for our login system to work properly, this page takes care of logout functionality (destroys session variables on logout)


    session_start(); session_destroy(); header('Location: index.php');?>

    A bit of Styling (style.css)

    h2{padding: 10px;}.homepage{margin-top: 50px; text-align: center;}th,td{border: 1px solid gray;padding:5px;}

    That's all we have built a simple yet powefull login sytem that supports multiple user roles. If you get into any trouble you can download the source code here Share your thoughts below using comment box.

    你可能感兴趣的:(PHP with MySql 多角色用户登录)