What Is the Difference Between Session and Cookies in PHP

Session and cookies both are used to store the user data as a global constant for the entire website. Even more, session and cookies both are store at client-side browser local storage. Now if both global constants have the same ability and functionality, how they are different from each other.

Session vs Cookies

As we discussed session and cookies both stores the user data in local storage at the client browser. But there is a major difference between them which makes them unique to each other.


Session is a global variable which stores the data in the client’s browser and it can be accessed on any webpage in the website. But the session is a short time storage and session is destroyed when the browser is closed.

Start a Session

To use the session constant first we have to initialize it in every web page where we want to access it.



Set a Session

After session initialization, we can set a session variable using the below syntax.



We can set a session with a unique key name and we can assign any variable of valid data type in PHP.

Unset a Session

We can unset any session value with the unset() function of PHP.



Destroy a Session

To clear all the sessions of our website there is an option of session destroy using sesssion_destroy() function. It clears all the sessions of the website.



Read More: PHP Session


Cookie is also a global constant like session. In addition, cookie stores the user data into the client’s web browser for a long time.

We can set the cookie duration as per our requirement. Generally, cookies are stored for 6 months to 1 year.

Set a Cookie

We can set a cookie by PHP inbuilt function setcookie() function.



In the above syntax, COOKIE_NAME is a required field and all others are optional fields.

  • COOKIE_NAME – To set a cookie name
  • COOKIE_VALUE – To set a cookie value
  • COOKIE_DURATION – To set a cookie expiry duration

Access a Cookie

We can use the below syntax to access cookies.




Cookie and sessions both are important to manage user data. Especially, all the web applications use session and cookies to manage user logins and activities.

I hope now you have a complete understanding of session and cookies.

Enjoy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

Read previous post:
New Line in PHP
How to Echo New Line in PHP

There are several ways to print a new line in PHP. Line break is quite important factor of content formatting...