We know that HTTP request is stateless which means any request doesn’t know anything about the user who is sending request i.e each HTTP transaction is fresh without having any knowledge of any other HTTP transaction. Both cookie and session are available to overcome the stateless request and both accomplish same task of storing data across multiple pages/request for a site. I would like to share a few differences between session and cookie:

  • Session data are stored at server side while cookie data are stored at client side. Cookie is being used to identify the user or user request i.e whenever a HTTP request is being send, browser sends cookie data to identify the request. If you see the cookies data of browser then you can see there will be “PHPSESSID” having string value and this will be send each time with request to identify session as well. The session is being stored at the server in some kind of text file (within the directory of server defined into php.ini as “session.save_path”) and this “PHPSESSID” be associated to identify that session.  As session is a process or server side mechanism which associate the all session data with session_id and serialize/un-serialize it whenever session is invoked. Also, on the server, garbage collecting process runs which destroy all the inactive sessions for a defined time (by default 1440 seconds set within php.ini as “session.gc_maxlifetime”).
  • Cookie is a text-only string (for Windows machines, cookie data is stored in cookie.txt file) while objects can be stored into session. The stored amount of cookie data is limited while session data is unlimited.
  • Cookies can be stored for future reference but session can’t i.e cookie will reside as browser data until detected.  While once browser closed session will destroy.  But we can say in other words, session data is stored as cookie with expiry date/time of zero which means that session will be active as long as browser. We can modify this behavior by changing the “session.cookie_lifetime” setting within “php.ini” to whatever time (in seconds) should be.