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).
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.
Set a Session
After session initialization, we can set a session variable using the below 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.
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.
Read More: PHP Session
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.
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.
Must Read: Cookies in PHP
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 🙂