萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php session_destroy()和session_unset()區別

php session_destroy()和session_unset()區別

本文章簡單的介紹一下關於session_destroy(),session_unset()區別說明,有需要的朋友可以參考一下。

session_unset()

You should know that on recent PHP only the first one of these functions works correctly. And if you use the other two, var_dump will print you the result you expected (session cleaned up), but the session file on the server won't be cleaned up. So use the first one.

 代碼如下 復制代碼

<?php

function session_clean1($logout=false)
 {
  $v=array();
  foreach($_SESSION as $x=>$y)
   if($x!="redirector"&&($x!="user"||$logout))
    $v[]=$x;

  foreach($v as $x)
   unset($_SESSION[$x]);
  return;
 }

function session_clean2($logout=false)
 {
  foreach($_SESSION as $x=>$y)
   if($x!="redirector"&&($x!="user"||$logout))
    unset($_SESSION[$x]);
  return;
 }

function session_clean3($logout=false)
 {
  $s=($logout||!isset($_SESSION["user"]))?array():
   array("user"=>$_SESSION["user"]);
  if(isset($_SESSION["redirector"]))
   $s["redirector"]=$_SESSION["redirector"];
  $_SESSION=$s;
 }

?>

On previous php (<<5.1.4) releases at least the third one worked correctly.

 

釋放當前在內存中已經創建的所有$_SESSION變量,但不刪除session文件以及不釋放對應的session id

session_destroy()

刪除當前用戶對應的session文件以及釋放session id,內存中的$_SESSION變量內容依然保留

因此,釋放用戶的session所有資源,需要順序執行如下代碼:

PHP代碼

 代碼如下 復制代碼

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

copyright © 萬盛學電腦網 all rights reserved