What Is the Difference Between Session and Cookies in PHP

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

Session vs Cookies

As we discussed, sessions and cookies store 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.

The major difference between sessions and cookies is the data storage duration at the client-side. Session destroys at browser close, and cookies expire after a specific time duration (generally 1 year).

Session

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

Start a Session

To use the session constant first, we have to initialize it on every web page to access it.

Syntax

session_start()

Set a Session

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

Syntax

$_SESSION['KEY'] = VALUE

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.

Syntax

unset($_SESSION['KEY'])

Destroy a Session

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

Syntax

session_destroy()

Read More: PHP Session

Cookies

A cookie is also a global constant like a session. Also, a 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.

Syntax

setcookie(COOKIE_NAME, COOKIE_VALUE, COOKIE_DURATION)

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.

Syntax

$_COOKIE['COOKIE_NAME']

Must Read: Cookies in PHP

Conclusion

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

I hope now you have a complete understanding of the 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. A line break is quite an important factor in...

Close