PHP- Session Example


solution      `: COOKIE
disadvantages: cookie size,no of cookie allows
another solution : 30..
ie. assigning each visitor a unique session ID.
and further store session id (SID) in cookie.
Problem : user can disable in browser.

URL rewriting:         :appending the SID to every local URL found within the requested page.
drawback: copying that URL into an e-mail and sending it to another user;
as long as the session has not expired, the session could continue on the
recipient’s workstation.
For these
reasons, the cookie-based methodology is recommended.

Note: Three of the most popular techniques for transmitting session IDs are
----URL session tracking,
----Hidden form elements,
-----and cookies.

  • session_start()
  • session_id(),
  • $_SESSION[],
  • unset(),
  • isset(),
  • session_unset(),
  • session_encode(),
  • session_decode(),


$sid = session_id();
// Encoded data retrieved from database looks like this:

// $sessionVars = username|s:5:"jason";loggedon|s:20:"Feb 16 2011 22:32:29";

echo "User ".$_SESSION['username']." logged on at ".$_SESSION['loggedon'].".";

Setting the Session Cookie Lifetime

The session.cookie_lifetime directive determines the session cookie’s period of validity. Its prototype
session.cookie_lifetime = integer
The lifetime is specified in seconds, so if the cookie should live 1 hour, this directive should be set to 3600. If this directive is set to 0 (the default),

an attack known as session-fixation involves an attacker somehow obtaining an unsuspecting user’s SIDand then using it to impersonate the user in order to gain access to potentially sensitive information.
boolean session_regenerate_id([boolean delete_old_session])
NOTE:The optional delete_old_session parameter determines whether the old session file will also be deleted when the session ID is regenerated. By default, this behavior is disabled.