PHP: session_unset() vs. session_destroy()

session_unset()

Will unset each element of the $_SESSION array.

  • It will not delete the session file created on disk by session_start().
  • It will not delete the cookie header set by session_start().
  • It will not delete the cookie from user’s browser (by setting a cookie header for example).
  • At the end of the script session_write_close() is still called automatically and whatever is set inside the $_SESSION array, it will be written to disk. This can mean an empty file if $_SESSION is empty or whatever was added in $_SESSION after session_unset() was called.
<?php
  session_start();
  $_SESSION['file'] = 'image.jpg';
  $_SESSION['counter'] = 5;
  //session_unset() is equivalent with the next two lines
  unset($_SESSION['file']);
  unset($_SESSION['counter']);

  $_SESSION['name'] = 'drona';
  print_r($_SESSION); //will print: Array ([name] => drona )
  //in server's session file: name|s:5:"drona";
?>

session_destroy()

Will delete the session file that is stored on the server’s disk and it will prevent the elements from the $_SESSION array to be saved in a file on server’s disk at the end of the script or on session_write_close().

  • Does not delete elements in the $_SESSION array.
  • It will not delete the cookie header set by session_start().
  • It will not delete the cookie from user’s browser (by setting a cookie header for example).
  • Variables from $_SESSION will not be saved in a session file at the end of the script unless you use session_start() again.
<?php
  session_start();
  $_SESSION['file'] = 'image.jpg';
  $_SESSION['counter'] = 5;
  session_destroy();
  $_SESSION['name'] = 'drona';
  print_r($_SESSION);// will print: Array ([file]    => image.jpg
                     //                    [counter] => 5
                     //                    [name]    => drona )
?>

 

Lasă un răspuns

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *