PHP - Basic user management code example


SUBMITTED BY: efbee

DATE: Oct. 3, 2016, 9:28 p.m.

FORMAT: PHP

SIZE: 2.0 kB

HITS: 962

  1. Basic Security
  2. <?php
  3. // START FILE: security.php
  4. session_start();
  5. $errorlogin = "Authentication Required"; // Text to display when login error
  6. $basicrealm = "Private Stuff"; // Displayed text on login form
  7. $authentication = Array (1=>Array("user1", "pass1"), // User and Pass for User-1
  8. 2=>Array("user2", "pass2"), // User and Pass for User-2
  9. 3=>Array("user3", "pass3"));// User and Pass for User-3
  10. class security {
  11. var $authentication = Array();
  12. var $errorlogin;
  13. var $basicrealm;
  14. function security() {
  15. global $authentication, $errorlogin, $basicrealm;
  16. $this->authentication = $authentication;
  17. $this->errorlogin = $errorlogin;
  18. $this->basicrealm = $basicrealm;
  19. }
  20. function secureMe() {
  21. global $_SESSION, $PHP_AUTH_USER, $PHP_AUTH_PW;
  22. if (trim($PHP_AUTH_USER)!=""&&trim($PHP_AUTH_PW)!="") {
  23. if($this->checkLogin($PHP_AUTH_USER, $PHP_AUTH_PW)) return true;
  24. }
  25. if (!$_SESSION||$_SESSION["passed"]!="") {
  26. $this->showLogin();
  27. return false;
  28. }
  29. }
  30. function showLogin() {
  31. global $login_error, $realms;
  32. header('WWW-Authenticate: Basic realm='.$this->basicrealm);
  33. header('HTTP/1.0 401 Unauthorized');
  34. print $this->errorlogin;
  35. exit();
  36. }
  37. function checkLogin($username, $password) {
  38. for($i=0;$i<count($this->authentication);$i++) {
  39. if($username == $this->authentication[$i][0] &&
  40. $password == $this->authentication[$i][1]) {
  41. $j++;
  42. }
  43. }
  44. if($j!=0) return true;
  45. }
  46. };
  47. // END FILE: security.php
  48. ?>
  49. Put the line below on the top of the page you wish to secured.
  50. <?php
  51. require_once("./security.php");
  52. $security = new security;
  53. if($security->secureMe()) $passed = "true"; session_register('passed');
  54. ?>

comments powered by Disqus