Simple rights management php

Keywords: PHP SQL Database JQuery

Forwarded from https://www.cnblogs.com/shenzikun1314/p/6604867.html#4262295

 

  • First, the basic theory to understand is whether the relationship between users, roles and privileges is one-to-many or many-to-many.From this, the table is created.

 

A user can belong to multiple roles, such as Dunchao.He is Sun Li's husband, his child's father, or his father's son.Here he has three roles: husband, father and son.

A role can have multiple users.Examples include students (roles), Zhang San, Li Si, Wang Wu, etc.

So users have a many-to-many relationship with roles.

 

A role can have multiple permissions.For example, divide the article module into four permissions: view, modify, add and delete.An average user has only view privileges, but an administrator can have all four at once.

A privilege can also be owned by multiple roles at the same time.Normal users and administrators have view privileges.

So permissions are also many-to-many with roles.

 

 

  • Start building tables below

First User Table

 

 

 

Second Role Table

 

 

 

Third Permission Table

 

 

Next are two intermediate tables.

User-Role Table (to set many-to-many foreign key associations)

 

 

Last Role-Permission Table (Setting up many-to-many associations)

 

 

 

 

  • Next is the code

The first guanli.php, using jquery syntax such as ajax, references the jquery file.This page is to modify the user's role permissions

 

 

 

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
        include("DB.class.php");
        $sql = "select * from qx_user";
        $arr = $dao->getAll($sql);
        // var_dump($arr);
        // exit;
        $sql = "select * from qx_juese";
        $arr2 = $dao->getAll($sql);
        foreach($arr as $v){
            // var_dump($v);
            // exit;
        }
        ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
        <script src="assets/js/jquery-1.8.2.min.js"></script>

<!-- <script src="../../dist/js/jquery-1.11.2.min.js"></script> -->
</head>

<body>

<h1>User and Role Management</h1>
<div>
//Please select a user:
    <select id="user">
        <?php foreach($arr as $v){
        //     var_dump($v);
        // exit;
         ?>

            <option value="<?php echo"$v[id]" ?>"> <?php echo "$v[username]";?></option>
        <?php } ?>
    </select>
</div>
<br />
<div>
//Please select a role:

<?php foreach($arr2 as $v2){ ?>
<input type='checkbox' value="<?php echo"$v2[id]" ?>" class='ck' /><?php echo "$v2[juese_name]" ?>
        <?php } ?>

</div>
<br />

<input type="button" value="Determine" id="btn" />

</body>
<script type="text/javascript">
$(document).ready(function(e) {
    //Select default role
    Xuan();
    //When the user selects a change, select the appropriate role
    $("#user").change(function(){
            Xuan();
        })
    //Click OK to save role information
    $("#btn").click(function(){
            var uid = $("#user").val();
            var juese = "";
            var ck = $(".ck");
            for(var i=0;i<ck.length;i++)
            {
                if(ck.eq(i).prop("checked"))
                {
                    juese += ck.eq(i).val()+"|";
                }
            }
            juese = juese.substr(0,juese.length-1);
            $.ajax({
                    url:"chuli.php",
                    data:{uid:uid,juese:juese,type:1},
                    type:"POST",
                    dataType:"TEXT",
                    success: function(data){
                            alert("Save successfully!");
                        }
                });
        })
});
//Select default role
function Xuan()
{
    var uid = $("#user").val();
    $.ajax({
        url:"chuli.php",
        data:{uid:uid,type:0},
        type:"POST",
        dataType:"TEXT",
        success: function(data){
                // var juese = data.trim().split("|");
                // var ck = $(".ck");
                // ck.prop("checked",false);
                // for(var i=0;i<ck.length;i++)
                // {
                //     if(juese.indexOf(ck.eq(i).val())>=0)
                //     {
                //         ck.eq(i).prop("checked",true);
                //     }
                // }
                // console.log(data);
                var obj = eval('(' + data + ')');
                console.log(obj);
                var str="";
                for(var i=0;i<obj.length;i++){
                    str+=" ";
                    str+=obj[i].juese_id;
                }
                str=$.trim(str)
                console.log($.trim(str));

                var ck = $(".ck");
                ck.prop("checked",false);
                for(var i=0;i<ck.length;i++)
                {
                    if(str.indexOf(ck.eq(i).val())>=0)
                    {
                        ck.eq(i).prop("checked",true);
                    }
                }
                
            }
        });
}
</script>
</html>

login.php, second login page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<h1>Logon Page</h1>
<form action="logincl.php" method="post">
<input type="text" name="username" />
<input type="password" name="pwd" />
<input type="submit" value="Sign in" />
</form>
</body>
</html>

The third page handles login page logincl.php

<?php
header('content-type: text/html; charset=utf-8');
session_start();
include("DB.class.php");
$username = $_POST["username"];
$pwd = $_POST["pwd"];
  // $uid=$_POST["uid"];

// $sql="select pwd from qx_user where uid='{$uid}'";
// $mm = $dao->getOne($sql); 

// if($mm==$pwd && !empty($pwd))
// {
//     $_SESSION["uid"]=$uid;
//     header("location:main.php");
// }


$username = $_POST['username'];
  // Obtain post Password passed in
   $password = $_POST['pwd'];
 

 $sql = "select * from qx_user where username = '$username' and pwd = '$pwd' ";
 $res = $dao->getRow($sql);



  
     if($res){//If it exists,Jump back to this page
        $_SESSION['username'] = $username;
        $_SESSION["uid"]=$res["id"];

          echo '<script language="JavaScript">;
          alert("Login Successful");location.href="main.php";</script>;';
          
          exit;

         
     }else{//If it does not exist
        
        echo '<script language="JavaScript">;
          alert("Logon Failure");</script>;';
        
        //Jump to the specified page after successful registration
        echo "<script>location.href='#'</script>";
     }

Page 4 View Privilege main.php, all privileges of the output logged-in user u1 versus u2

 

 

Second login u2

 

 

 

<?php  session_start(); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<h1>
//Current user:<?php echo "$_SESSION[username]";?>
</h1>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);

// session_start();
include("DB.class.php");

if(empty($_SESSION["uid"]))
{
    header("location:qx_login.php");
    exit;
}
//Logon user name
$uid = $_SESSION["uid"];


//Look up roles by user name
$sjs = "select juese_id from qx_user_juese where user_id='{$uid}'";
$ajs = $dao->getAll($sjs);
// var_dump($ajs);
// exit;
//Define an array to hold the function code
$arr = array();
//Look up function codes based on role codes
foreach($ajs as $vjs)
{
        $jsid = $vjs['juese_id']; //Role Code
        $sgn = "select quanxian_id from qx_js_qx where juese_id='{$jsid}'";
        $strgn = $dao->getAll($sgn);
        // $agn = explode("|",$strgn);
        // var_dump($strgn);
        // echo "xxx";
        // exit;
        foreach($strgn as $vgn)
        {
            
            array_push($arr,$vgn['quanxian_id']);

            
        }    
}

//Weight removal, display
// var_dump($arr);
//         exit;
$arr = array_unique($arr);
// var_dump($arr);
//         exit;
foreach($arr as $v)
{
    $sql = "select * from qx_quanxian where id='{$v}'";
    $attr = $dao->getRow($sql);

    
    
     // var_dump($attr);
     //     exit;
     // echo "{$attr['id']},{$attr['qx_name']}";
     echo "<div code='{$attr["id"]}'>{$attr["qx_name"]}</div>";
    // <input type='checkbox' value="$attr[id]" class='ck' />
        
}

?>



</body>
</html>

The fifth tool class code, DB.class.php, modifies the default configuration parameters, database name, user name, password, and so on, in the constructor u construct().Otherwise, the connection to the database will fail.

<?php
// namespace Frame\libs;
class DB{
    //Host Address
    var $host;
    //User name
    var $username;
    //Password
    var $password;
    //Database Name
    var $dbname;
    //character set
    var $charset;
    //Database connection object, mainly used for mysql_query($sql,$this->con);
    private $con;
    //Externally acquired mysqlDB Class Operating Objects
    public static $dao;
    //Get mysqlDB Class object(Singleton)
    public static function getInstance($config){
        if(!isset(self::$dao)){
            self::$dao = new self($config);
        }
        return self::$dao;
    } 
    //private Prohibit External new,reduce new Overhead incurred and default configuration set.
    private function __construct($config){
        $this->host = isset($config['host'])?$config['host']:'localhost';
        $this->port = isset($config['port'])?$config['port']:'3306';
        $this->username = isset($config['username'])?$config['username']:'root';
        $this->password = isset($config['password'])?$config['password']:'root';
        $this->dbname = isset($config['dbname'])?$config['dbname']:'bishe';
        $this->charset = isset($config['charset'])?$config['charset']:'utf8';
        //Connect to database
        $this->con = $this->connect();
        //Set database name, default is test
        $this->useDb($this->dbname);
        //Set character set, default is utf8.  
        $this->setCharset($this->charset);

    }
    //Prohibit external cloning
    private function __clone(){

    }
    //The connection was not successfully found in this segment.
    //////////////////////////////////////////////////////
    //Connect to database
    public function connect(){
         $con = 
        mysql_connect("$this->host:$this->port","$this->username","$this->password") or die("Failed to connect to database");
        return $con;
    }
    //1.Perform additions, deletions, changes sql Sentence 
    public function exec($sql){
        $res = mysql_query($sql,$this->con);
        if($res){
             // echo "<br/>sql Sentence:".$sql."<br>";
             // var_dump($res);
             return true;
             
            //If there are problems with additions or deletions, you can output them here sql Debugging.
        }else{
            echo "<br/>sql Sentence:".$sql;
            echo "<br/Error message>: ".mysql_error();
            echo "<br/Error Code>: ".mysql_errno();
            exit;
        }
    }
    //Extra Set Character Set
    public function setCharset($charset){
        $sql = "set names '$charset'";
        $this->exec($sql) or die("set");
        //die();
    }
    //Extra database settings
    public function useDb($dbname){
        $sql = "use $dbname";
        $this->exec($sql) or die("use");//or die()Return the corresponding before the function true or false;
    }
    ////////////////////////////////////////////////////////
    //Find out what went wrong in this section.
    //4. Turn the result set found into a single data, here is the first field of the index array.
    public function getOne($sql){
        $rec = mysql_query($sql,$this->con);
        $res = mysql_fetch_row($rec);
        if($res){
            return $res[0];
        }else{
            return false;
        }
    }
    //Possibly modified functions are all placed on top for easy lookup.The following functions will not be modified at all.
    //Numbers 1~4 are functions used frequently.
    //2. Get a row of data (one-dimensional)
    public function getRow($sql){
        $rec = mysql_query($sql,$this->con);
        $res = mysql_fetch_assoc($rec);
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    //3.Get all the data (2-D)
    public function getAll($sql){
        $rec = mysql_query($sql,$this->con);
        $arr = array();//Define an array
        while($res = mysql_fetch_assoc($rec)){
            $arr[] = $res;
        }
        if($arr){
            return $arr;
        }else{
            return false;
        }
    }

}

$dao = DB::getInstance(null);
?>

The sixth chuli.php. page is used to handle ajax requests from guanli.php.

<?php
error_reporting(E_ALL ^ E_DEPRECATED);

include("DB.class.php");


$type = $_POST["type"];

switch($type)
{
    case 0:
        $uid = $_POST["uid"];
        $sql = "select juese_id from qx_user_juese where user_id='{$uid}'";
        $data = $dao->getAll($sql);
        // $id_list="xx";
        // foreach($data as $v)
        // {
            
        //     $id_list =","+"$v[juese_id]";

        //     echo json_encode($id_list);
        //     exit;


        // }
            // echo json_encode($data);

        echo json_encode($data);
        break;
    case 1:
        $uid = $_POST["uid"];
        $juese = $_POST["juese"];
        $sdel = "delete from qx_user_juese where user_id='{$uid}'";
        $dao->exec($sdel);
        $arr = explode("|",$juese);
        foreach($arr as $v)
        {
            // echo $v;
            $sql = "insert into qx_user_juese values('{$uid}','{$v}')";
            $dao->exec($sql);
        }
        echo "OK";
        break;
}

The challenge is the ajax request on the guanli page.

 

 

js parsing two-dimensional array

 

 

 

 

 

 

 

 

(finished)

Posted by billborric on Thu, 21 Nov 2019 19:49:56 -0800