Ending a Session

At some point in an application, sessions may need to be destroyed. For example, when a user logs out of an application, a call to the session_destroy( ) function can be made. A call to session_destroy( ) removes the session file from the system but doesn't remove the PHPSESSID cookie from the browser.

Example 8-3 shows how the session_destroy( ) function is called. A session must be initialized before the session_destroy( ) call can be made. You should also test to see if $PHPSESSID is a set variable before killing the session. This prevents the code from creating a session, then immediately destroying it if the script is called without identifying a session. However, if the user has previously held a session cookie, PHP initializes the $PHPSESSID variable, and the code redundantly creates and destroys a session.

session_destroy function

session_destroy destroys all data registered to a session. To use the session variables again, session_start() function has to be called.

session_destroy() destroys all of the data associated with the current session but it does not unset any of the global variables associated with the session, or unset the session cookie.

Example 8-3. Ending a session
  // Only attempt to end the session if there
  // is a $PHPSESSID set by the request.
  if(isset($PHPSESSID)) {
    $message = "<p>End of session ($PHPSESSID).";
    session_start(  );
    session_destroy(  );
  } else {
    $message = "<p>There was no session to destroy!";
   "-//W3C//DTD HTML 4.0 Transitional//EN"
   "" >

by BrainBellupdated