Guest User

Untitled

a guest
Oct 15th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. <?php
  2.  
  3. class SessionManager{
  4.  
  5. /*
  6. SETTINGS FOR OUR SESSION
  7. SESSION_NAME - Name of our session
  8. ACTIVE_DAYS - Number of days you want the session to be active
  9. */
  10. public const SETTINGS=[
  11. "SESSION_NAME"=>"SHOPPING",
  12. "ACTIVE_DAYS"=>2
  13. ];
  14.  
  15.  
  16. public function __construct(){
  17. session_start();
  18. // setting name to our session
  19. session_name(self::SETTINGS["SESSION_NAME"]);
  20. }
  21.  
  22. public function loginUser($userName){
  23. /*
  24. change paramter $userName as per your requirement
  25. $sessionData contains the information we are saving into the session.
  26. lastLogin - date and time when the user logged into his account
  27. */
  28. $sessionData=[
  29. "userName"=>$userName,
  30. "lastLogin"=>date('Y-m-d H:i:s')
  31. ];
  32. $_SESSION['account']=$sessionData;
  33. session_write_close();
  34. }
  35.  
  36. public function logoutUser(){
  37. unset($_SESSION['account']);
  38. }
  39.  
  40. public function isSessionValid(){
  41. /*
  42. Returns true
  43. if there is a session
  44. and
  45. the difference between the day user accessed the page and user logged into the page
  46. is less than ACTIVE_DAYS specified in SETTINGS
  47. */
  48. $currentLogin=new DateTime(date('Y-m-d H:i:s'));
  49. $lastLogin=new DateTime($_SESSION['account']['lastLogin']);
  50. $daysDifference=$currentLogin->diff($lastLogin)->format('%a');
  51. return ((isset($_SESSION['account']) && ($daysDifference) < self::SETTINGS["ACTIVE_DAYS"])) ? true : false ;
  52. }
  53. }
  54.  
  55.  
  56.  
  57. /*
  58.  
  59. ------------- Usage ------------------------
  60. Assuming you have included above code in these files
  61. for eg : include('sessionmanager.php');
  62. */
  63.  
  64. /* ------------ Login.php ------------------------- */
  65.  
  66. $s=new SessionManager();
  67. $s->loginUser("John Doe");
  68. echo "Login successfull";
  69.  
  70. /* ------------- Home.php ---------------------------*/
  71.  
  72. $s=new SessionManager();
  73. if($s->isSessionValid()){
  74. echo "Hello {$_SESSION['account']['userName']}";
  75. }
  76. else{
  77. $s->logoutUser();
  78. echo "You need to login again";
  79. }
  80.  
  81. /* -------------- Logout.php ------------------------ */
  82.  
  83. $s=new SessionManager();
  84. $s->logoutUser();
  85. echo "Logged out";
  86.  
  87.  
  88. ?>
Add Comment
Please, Sign In to add comment