Advertisement
Guest User

simple login example

a guest
Feb 27th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.23 KB | None | 0 0
  1. <?php
  2.  
  3. global $db = null; // db connection
  4.  
  5. $user_id = "";
  6. $password = "";
  7.  
  8. /**
  9.  * This function will fetch a specific user fro mthe database;
  10.  *
  11.  * @param int $user_id The user id;
  12.  * @return Object it's fetched object. null will be returned if anything goes wrong.
  13.  **/
  14. function get_user($user_id) {
  15.     // validating input
  16.     // must not be empty or not a number nor a negative number
  17.     if (empty($user_id) || !is_numeric($user_id) || $user_id <= 0 ) {
  18.         return null;
  19.     }
  20.    
  21.     // query to the db
  22.     // please adjust to your case
  23.     $user = $db->query("select * from users where id =  " . $user_id . ";");
  24.    
  25.     // returning values
  26.     return ($user) ? $user : null;
  27. }
  28.  
  29. function has_privilege($user_id, $role) {
  30.     $query = $db->query("select * from roles where user_id = " . $user_id . ";");
  31.    
  32.     return ($role == $query['role']);
  33. }
  34.  
  35. $user = get_user($user_id);
  36.  
  37. // loging in
  38. // this presumes you're using PHP built-in validation functions see manual
  39. if (password_verify($password, $user['password'])) {
  40.     // checking if it has required privileges...
  41.     if (has_privilege($user_id, "admin")) {
  42.         // grant access
  43.         header("location: ... "); // your page
  44.     } else {
  45.         // error. redirect to login
  46.     }
  47. } else {
  48.     // error. redirect to login
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement