PHP - State management - State management

State management

  • In web application, it is frequently desirable to
  • Remember if user has visited a site previously
  • Remember the sequence of pages visited during a session
  • Associate information with a user session
  • To accomplish these thing need have “Stateful” connections between client and server
  • That is, associated information (state) with the connection
  • HTTP was originally designed to not be stateful, leading to the addition of the cookies machine

  • PHP Session

    The solution: store session information on the server, and have the client only store an identifier for its information as stored on the server.

    The identifier is known as a session ID. The session ID is stored using a cookie (can be passed as a GET parameter as well)

    The server then uses the session ID to retrieve the information it has stored on the server.

    Session information is typically stored in files on the server, though options exist for using shared memory, and also writing your own handlers (e.g., to use a database for storage)


    Cookies are used to remember the users. Content of a Persistent cookie remains unchanged even when the browser is closed. ‘Remember me’ generally used for login is the best example for Persistent Cookie

    1. A mechanism for adding state to HTTP request
    2. Permits name, value pairs to be preserved across multiple approach
    3. Basic approach
    4. Servers sends a set –cookies HTTP header in its response
    5. Value of header includes name, value pairs
    6. The client stores the name, value pairs and proactively sends them to the server (in the cookies header) with every request thereafter
    7. The cookies protocol piggybacks on top of HTTP

    How to set cookies in PHP?

  • Cookies are often used to track user information.
  • Cookies can be set in PHP using the setcookie() function.
  • Parameters are : name of the cookie, Value of cookie, time for expiry of cookie, path of the cookies location on server, domain, secure (TRUE or FALSE) indication whether the cookie is passed over a secure HTTPS, http only (TRUE) which will make the cookie accessible only through HTTP.
  • Returns TRUE or FALSE depending on whether the cookie was executed or not.