81

What is the distinction between Sessions and Cookies in PHP?

Harsh
  • 2,078
  • 6
  • 22
  • 37
  • 8
    Do we agree that both the question and the answers are language agnostic and not specific to PHP? If so, shouldn't be the question edited? – Augustin Riedinger Sep 29 '17 at 15:56

8 Answers8

117

A cookie is a bit of data stored by the browser and sent to the server with every request.

A session is a collection of data stored on the server and associated with a given user (usually via a cookie containing an id code)

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • @Quentin:) cookies can also store in session ? – Harsh Jun 14 '11 at 06:22
  • 3
    Also session values are reset after the connection is closed. Cookies values are normally saved. – BadSkillz Jun 14 '11 at 06:24
  • 1
    @poter — If a piece of data is stored on the server, then it isn't being stored by the browser (copies of data not withstanding), so no, you can't store a cookie in a session. – Quentin Jun 14 '11 at 06:26
  • 2
    @BadSkillz — no. Session values are usually reset after a period of time has passed without a connection from the client with which the session is associated. Cookie values are saved until their expiry time (or the browser is closed if one isn't set). Expire immediately overrides are available for both. – Quentin Jun 14 '11 at 06:28
  • @Quentin:) but when we again open our browser then it still remain saved cookies – Harsh Jun 14 '11 at 06:31
  • @porter — no. As I said, if don't specify an expiry time for a cookie, then it will be deleted when the browser is closed. (And if an expiry time is set, then the cookie will be deleted if that time has passed before the browser is reopened). – Quentin Jun 14 '11 at 06:32
  • @Quentin:) kkkk and both are using to pass the variable or store the variable ? – Harsh Jun 14 '11 at 06:34
  • @poter — that question doesn't parse. – Quentin Jun 14 '11 at 06:35
  • @Quentin, some browsers do not delete cookies with no expiry time, when browser is closed. E.g., Firefox 3.6 does that, when setting "*When Firefox starts*" is set to "*Show my windows and tabs from last time*". – binaryLV Jun 14 '11 at 06:38
  • @Quentin — why there is a session storage manager in the Google Chrome browser then if you say session is managed by the server? – edam Aug 07 '19 at 11:19
  • @edam — Please read the question. It says, twice, "in PHP". Other kinds of session are not relevant to the topic at hand. – Quentin Aug 07 '19 at 12:01
56

Cookies are used to identify sessions. Visit any site that is using cookies and pull up either Chrome inspect element and then network or FireBug if using Firefox.

You can see that there is a header sent to a server and also received called Cookie. Usually it contains some personal information (like an ID) that can be used on the server to identify a session. These cookies stay on your computer and your browser takes care of sending them to only the domains that are identified with it.

If there were no cookies then you would be sending a unique ID on every request via GET or POST. Cookies are like static id's that stay on your computer for some time.

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session.save_path location and actually "see sessions". They are either files on the server filesystem or backed in a database.

Screenshot of a Cookie

toomasr
  • 4,731
  • 2
  • 33
  • 36
  • Additional points for pointing to firebug and chrome dev tools. – Dhawan Gayash Jul 23 '13 at 01:12
  • I lost information on session and cookie is active, that causes error on app, why is the best way to maintain session? I store data on session but laravel maintan user login by cookie and data on session is gone. what can i do or read? – Rubén Ruíz Aug 22 '17 at 16:06
  • (that pass on Laravel Framework, that is my trouble) – Rubén Ruíz Aug 22 '17 at 16:09
  • is session different than storing things in database? – Suraj Jain Dec 29 '17 at 11:56
  • Most of the time, out of the box, session data is stored somewhere on disk. So for the case of Apache and PHP it is stored in the system temp folder or you can configure it to be stored somewhere else. Even in a database! – toomasr Jan 05 '18 at 13:10
21

The main difference between a session and a cookie is that session data is stored on the server, whereas cookies store data in the visitor’s browser.

Sessions are more secure than cookies as it is stored in server. Cookie can be turned off from browser.

Data stored in cookie can be stored for months or years, depending on the life span of the cookie. But the data in the session is lost when the web browser is closed.

Pang
  • 9,564
  • 146
  • 81
  • 122
Armin John
  • 337
  • 3
  • 10
16

Cookie

  • is a small amount of data saved in the browser (client-side)

  • can be set from PHP with setcookie and then will be sent to the client's browser (HTTP response header Set-cookie)

  • can be set directly client-side in Javascript: document.cookie = 'foo=bar';

  • if no expiration date is set, by default, it will expire when the browser is closed.
    Example: go on http://example.com, open the Console, do document.cookie = 'foo=bar';. Close the tab, reopen the same website, open the Console, do document.cookie: you will see foo=bar is still there. Now close the browser and reopen it, re-visit the same website, open the Console ; you will see document.cookie is empty.

  • you can also set a precise expiration date other than "deleted when browser is closed".

  • the cookies that are stored in the browser are sent to the server in the headers of every request of the same website (see Cookie). You can see this for example with Chrome by opening Developer tools > Network, click on the request, see Headers:

    enter image description here

  • can be read client-side with document.cookie

  • can be read server-side with $_COOKIE['foo']

  • Bonus: it can also be set/get with another language than PHP. Example in Python with "bottle" micro-framework (see also here):

    from bottle import get, run, request, response
    @get('/')
    def index():
        if request.get_cookie("visited"):
            return "Welcome back! Nice to see you again"
        else:
            response.set_cookie("visited", "yes")
            return "Hello there! Nice to meet you"
    run(host='localhost', port=8080, debug=True, reloader=True)
    

Session

  • is some data relative to a browser session saved server-side

  • each server-side language may implement it in a different way

  • in PHP, when session_start(); is called:

    • a random ID is generated by the server, e.g. jo96fme9ko0f85cdglb3hl6ah6
    • a file is saved on the server, containing the data: e.g. /var/lib/php5/sess_jo96fme9ko0f85cdglb3hl6ah6
    • the session ID is sent to the client in the HTTP response headers, using the traditional cookie mechanism detailed above: Set-Cookie: PHPSESSID=jo96fme9ko0f85cdglb3hl6ah6; path=/:

      enter image description here

      (it can also be be sent via the URL instead of cookie but not the default behaviour)

    • you can see the session ID on client-side with document.cookie:

      enter image description here

  • the PHPSESSID cookie is set with no expiration date, thus it will expire when the browser is closed. Thus "sessions" are not valid anymore when the browser is closed / reopened.

  • can be set/read in PHP with $_SESSION

  • the client-side does not see the session data but only the ID: do this in index.php:

    <?php
    session_start();
    $_SESSION["abc"]="def";
    ?>
    

    The only thing that is seen on client-side is (as mentioned above) the session ID:

    enter image description here

  • because of this, session is useful to store data that you don't want to be seen or modified by the client

  • you can totally avoid using sessions if you want to use your own database + IDs and send an ID/token to the client with a traditional Cookie

Basj
  • 41,386
  • 99
  • 383
  • 673
14

A session is a chunk of data maintained at the server that maintains state between HTTP requests. HTTP is fundamentally a stateless protocol; sessions are used to give it statefulness.

A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
seand
  • 5,168
  • 1
  • 24
  • 37
  • I lost information on session, you can say me why is the best way to solve that? read my coment on @toomasr solution please – Rubén Ruíz Aug 22 '17 at 16:08
5

Cookies are stored in browser as a text file format.It stores limited amount of data, up to 4kb[4096bytes].A single Cookie can not hold multiple values but yes we can have more than one cookie.

Cookies are easily accessible so they are less secure. The setcookie() function must appear BEFORE the tag.

Sessions are stored in server side.There is no such storage limit on session .Sessions can hold multiple variables.Since they are not easily accessible hence are more secure than cookies.

Ayush Chaurasia
  • 345
  • 4
  • 9
Elangovan
  • 3,469
  • 4
  • 31
  • 38
2

One part missing in all these explanations is how are Cookies and Session linked- By SessionID cookie. Cookie goes back and forth between client and server - the server links the user (and its session) by session ID portion of the cookie. You can send SessionID via url also (not the best best practice) - in case cookies are disabled by client.

Did I get this right?

Sam-T
  • 1,877
  • 6
  • 23
  • 51
1

Session

Session is used for maintaining a dialogue between server and user. It is more secure because it is stored on the server, we cannot easily access it. It embeds cookies on the user computer. It stores unlimited data.

Cookies

Cookies are stored on the local computer. Basically, it maintains user identification, meaning it tracks visitors record. It is less secure than session. It stores limited amount of data, and is maintained for a limited time.

Pang
  • 9,564
  • 146
  • 81
  • 122