Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class SessionManager{
- /*
- SETTINGS FOR OUR SESSION
- SESSION_NAME - Name of our session
- ACTIVE_DAYS - Number of days you want the session to be active
- */
- public const SETTINGS=[
- "SESSION_NAME"=>"SHOPPING",
- "ACTIVE_DAYS"=>2
- ];
- public function __construct(){
- session_start();
- // setting name to our session
- session_name(self::SETTINGS["SESSION_NAME"]);
- }
- public function loginUser($userName){
- /*
- change paramter $userName as per your requirement
- $sessionData contains the information we are saving into the session.
- lastLogin - date and time when the user logged into his account
- */
- $sessionData=[
- "userName"=>$userName,
- "lastLogin"=>date('Y-m-d H:i:s')
- ];
- $_SESSION['account']=$sessionData;
- session_write_close();
- }
- public function logoutUser(){
- unset($_SESSION['account']);
- }
- public function isSessionValid(){
- /*
- Returns true
- if there is a session
- and
- the difference between the day user accessed the page and user logged into the page
- is less than ACTIVE_DAYS specified in SETTINGS
- */
- $currentLogin=new DateTime(date('Y-m-d H:i:s'));
- $lastLogin=new DateTime($_SESSION['account']['lastLogin']);
- $daysDifference=$currentLogin->diff($lastLogin)->format('%a');
- return ((isset($_SESSION['account']) && ($daysDifference) < self::SETTINGS["ACTIVE_DAYS"])) ? true : false ;
- }
- }
- /*
- ------------- Usage ------------------------
- Assuming you have included above code in these files
- for eg : include('sessionmanager.php');
- */
- /* ------------ Login.php ------------------------- */
- $s=new SessionManager();
- $s->loginUser("John Doe");
- echo "Login successfull";
- /* ------------- Home.php ---------------------------*/
- $s=new SessionManager();
- if($s->isSessionValid()){
- echo "Hello {$_SESSION['account']['userName']}";
- }
- else{
- $s->logoutUser();
- echo "You need to login again";
- }
- /* -------------- Logout.php ------------------------ */
- $s=new SessionManager();
- $s->logoutUser();
- echo "Logged out";
- ?>
Add Comment
Please, Sign In to add comment