简体   繁体   中英

Restrict PHP page from specific user

Let's say I have a database named users and it has 3 users:

  uid | a_id | username | password
  1   |  1   | William  | 123
  2   |  2   | Joe      |321

a_id refers to "access id", meaning that 1 is admin and 2 is guest.

I want users with a_id of 2 to not be able to see or click on examplepage1.php

Here's the code I used for my login:

 <?php
 try {
 $db = new PDO('mysql:host=localhost;dbname=login', "root", "");
 } catch (PDOException $e) {
 echo $e->getMessage();
 }

    $uid = $_POST['username1'];
    $pwd = $_POST['password1'];

    $sql = "SELECT * FROM `users` WHERE  `username` = :username1 AND `password` = :password1";
   $statement = $db->prepare($sql);
    $userData = [
'username1'=>$uid,
'password1'=>$pwd,

    ];

   $statement->execute($userData);

   if($statement->rowCount() > 0){
   session_start();
   $_SESSION['admin']= $uid;
   $_SESSION['logged'] = true;

   header('Location: indextemplate.php');
   exit();
 }

   elseif ($uid!=$idvariable&$pwd!=$idvarible){
   header('Location: loginform.php?error=empty2');
  exit();
 }
 ?>

and at every start of a page I put:

<?php
  session_start();
   if(!isset($_SESSION['admin'])){
   header('location:index1.php');
   }
   else
   { 
 *my website here*
  }
 ?>

store your a_id when you logged in with username and password. and check

<?php
  session_start();
   if(isset($_SESSION['a_id']) && $_SESSION['a_id'] == 1){
   header('location:index1.php');
   }
   else
   { 
 *my website here*
  }
 ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM