PHP: Sessions vs Cookies

Posted by on in How to
  • Font size: Larger Smaller
  • Subscribe to this entry

HTTP is a stateless protocol, which means that as soon as a page has been sent to the client and the connection is closed any data that has been stored is lost. As a PHP Developer, you often need a way of storing information across multiple pages of your website. The potential uses for this are many. A few examples would be tracking if a user has logged in or perhaps remembering previously set preferences for custom user pages. The common way of accomplishing this via PHP is with sessions and cookies.

Cookies

A cookie is a small file that is stored on the client computer when visiting a website. Cookies got a bad rap a few years ago and as a result there is a good deal of people out there with their cookies disabled. Cookies are harmless. Some sites will use them to track visitor usage and habits and people sometimes consider that an invasion of privacy, but it typically is not a problem.

Here are some of the features of a cookie:
  • Stored on the client computer and are thus decentralized.
  • Can be set to a long lifespan and/or set to expire after a period of time from seconds to years.
  • They work well with large sites that may use several webservers.
  • Won't do you any good if the client has set their browser to disable cookies.
  • Limitations on size and number: a browser can keep only the last 20 cookies sent from a particular domain, and the values that a cookie can hold are limited to 4 KB in size.
  • Can be edited beyond your control since they reside on the client system.
  • Information set in the cookie is not available until the page is reloaded.

Sessions

Sessions are a combination of a server-side cookie and a client-side cookie, where the client-side cookie is simply a reference id to the information stored in the server-side cookie.

Here are some features of sessions :
  • Server-size cookie can store very large amounts of data while regular cookies are limited in size.
  • Since the client-side cookie generated by a session only contains the id reference (a random string of 32 hexadecimal digits, such as 'fca17f071bbg9bf7f85ca281653499a4' called a 'session id') you save on bandwidth.
  • Much more secure than regular cookies since the data is stored on the server and cannot be edited by the user.
  • Only last until the user closes their browser.
  • Won't work if client has cookies disabled in their browser unless some extra measures are taken (example below).
  • Can be easily customized to store the information created in the session to a database. (example here)
  • Information is available in your code as soon as it is set.

How to use Sessions when Cookies are Disabled

If cookies are disabled you must use a different method to pass the session id. A popular method is to pass it in the querystring and then process it in the subsequent page using $_GET, like so:

echo "http://www.yoursite.com/yourphppage.php?PHPSESSID=".session_id();
Then use the following in the loading page to retrieve the session id:
echo $_GET['PHPSESSID'];

When to use one over the other

Cookies generally should be used for non-sensitive 'throw-away' information like the following:

  • Displaying the users name next time they visit the site.
  • Simple user display preferences.
  • Anything small and disposable that needs to be stored for a period of time (for info like, email address, contact info etc. a database should be used)

Sessions are used for more sensitive info like controlling user access or loading info from a database that expires when the session ends or the browser window is closed.

Sources

The source of the above information is a combination of experience, various articles and sites on the web. The most influential being The Practical PHP Programming Wiki and php.net.

Last modified on
Tagged in: code Cookies PHP
Trackback URL for this blog entry.
Dustin is a web technologist from Wisconsin USA with over 12 yrs. experience consulting entrepreneurs, businesses and local government in web technology. Recently, he's been a bit of a Joomla nut.
  • Guest
    Nile Friday, January 25, 2008

    Well is there a more secure method then using get?
    get is a pretty un-secure function and easy to hack.

  • Admin Dustin
    Dustin Monday, October 28, 2013

    Nile, you are absolutely correct, using GET is easily hacked. There are other more complex options you could use. For example, you could store certain information about each client in a temporary location on the server (like their IP and login) and then check against that for each subsequent page. However, this would also be prone to security and performance issues. As with all security, on and off the web, the best method is to have multiple lines of defense.

    In any event, with the standard being that cookies typically are enabled you can simply deny access to visitors who don't accept cookies with a polite message like "To view this site you must first enable cookies in your browser". Then give some instruction on enabling them. That being said, always code to accommodate your target market and the technology they are actually using.

  • Guest
    Gabe Sunday, June 29, 2008

    Nice write up on that :)

  • Guest
    Rakshith Tuesday, March 3, 2009

    Nicely explained

  • Guest
    alapati Wednesday, November 4, 2009

    from this i understand that cookies and sessions their are slight difference .sometimes sessions r stored like a cookie

  • Guest
    padmaja Wednesday, November 4, 2009

    cookies means to pass the information one page to another page in one application.
    session means what changes made in an application browser

  • Guest
    Abe Thursday, January 14, 2010

    @alapati

    Sessions and cookie are stored in a very similar way.
    The main difference is the simple fact users can't edit their own sessions as they are server based.

    As a rule, this makes them more secure when dealing with sensetive information.

    A great comparative article, thanks!

  • Guest
    arun Tuesday, April 6, 2010

    very helpful ....

    but I have a question for you though ... can we use sessions and still support the "keep me logged in" feature? or do we have to use cookies for that?

    thanks.

  • Guest
    Rbrilliant Wednesday, August 4, 2010

    Nice concise article!

  • Guest
    Wigunawan Saturday, October 16, 2010

    is PHP resends "Set-Cookie" header before max-age or expiration of session?
    is PHP always store/create server's cookie every session_start executed? even it's blank data?

  • Guest
    PG Thursday, June 17, 2010

    Excellent explanation, but one question though, I cannot see a session ID cookie stored on my PC, how come?

    Thank you!

Leave your comment

Guest Thursday, April 24, 2014