PHP Sessions

Jun 15, 2009 Author: LinuxAdmin

HTTP is a stateless protocol; this means that the webserver does not know (or care) whether two requests comes from the same user; each request is instead handled without regard to the context in which it happens.

Sessions are used to create a measure of state in between requests—even when they occur at large time intervals from each other. Sessions are maintained by passing a unique session identifier between requests— typically in a cookie, although it can also be passed in forms and GET query arguments. PHP handles sessions transparently through a combination of cookies and URL rewriting, when session.use_trans_sid is turned on in php.ini (it is off by default in PHP5) by generating a unique session ID and using it track a local data store (by default, a file in the system’s temporary directory) where session data is saved at the end of every request. Sessions are started in one of two ways.

You can either set PHP to start a new session automatically whenever a request is received by changing the session.auto_start configuration setting in your php.ini file, or explicitly call session_start() at the beginning of each script. Both approaches have their advantages and drawbacks. In particular, when sessions are started automatically, you obviously do not have to include a call to session_start() in every script. However, the session is started before your scripts are executed; this denies you the opportunity to load your classes before your session data is retrieved, and makes storing objects in the session impossible. In addition, session_start() must be called before any output is sent to the browser, because it will try to set a cookie by sending a response header. IMPORTANT:In the interest of security, it is a good idea to follow your call to session_start() with a call to session_regenerate_id() whenever you change a user’s privileges to prevent “session fixation” attacks. We explain this problem in greater detail later in the Security chapter.

tags: Sessions

views 3580
  1. Add New Comment