简体   繁体   中英

Removing / Timing / Destroying out multiple php sessions variables at once

I'm trying to get several session variables to timeout / destroy at 30 minutes but using as minimal but effective code as possible.

Right now I have two solutions as follows:

if(isset($_SESSION['fullname']) && (time() - $_SESSION['fullname'] > 1800)) {
    session_unset();
    session_destroy();
}
$_SESSION['fullname'] = time();

  session_start();
  $user_inactive = 1800;
  $user_session = time() - $_SESSION['current_user'];
  if($user_session > $user_inactive) { 
     session_destroy(); 
     header("location: logout.php"); 
  }
  $_SESSION['current_user']=time();

Both these work fine for single variables, However i am trying to get this to destory several variables at the same time such as:

  1. Fullname
  2. Phonenumber
  3. Emailaddress

and so on...

Could someone be kind enough to advise me on the best way to go about this in order to destroy multiple variables without having to duplicate my code over and over again for each variable.

NewLeaner as your aware from my last question i answered for you, I'm still learning the basics myself so i am far from experienced however i overcome a problem like this during the coding of my own application and as Darren mentioned in a previous comment , Having a list of variable values within an array will allow you to unset the relevant sessions accordingly based on the array values matching the session variable values.

Below is an example of your session variable values:

  1. Fullname Session: $_SESSION['fullname']
  2. Phonenumber Session: $_SESSION['Phonenumber']
  3. Emailaddress Session: $_SESSION['Emailaddress']

$unset = array('Fullname','Phonenumber','Emailaddress'); 
foreach( $unset as $sessions ) {
    unset($_SESSION[$sessions]); 
}

This will unset and remove the above sessions such as Fullname, Phonenumber, Emailaddress and any others you wish to add to the array.

You can add more Values to the array using single quotes and comma seperated, Here is an example to add further values.

$unset = array('Fullname','Phonenumber','Emailaddress', 'Variable_4', 'Variable_5', 'Variable_6', 'Variable_7', 'And so on...');

Hope this helps once again!

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