Cookies and Sessions

πŸ“˜ PHP πŸ‘ 27 views πŸ“… Dec 22, 2025
⏱ Estimated reading time: 2 min

What are Cookies and Sessions?

Cookies and Sessions are used to store user data temporarily to maintain state across multiple pages in a web application.

  • Cookies store data on the user’s browser

  • Sessions store data on the server


Cookies in PHP

What is a Cookie?

A cookie is a small piece of data stored in the user's browser. It is mainly used for user preferences, tracking, and authentication.


Creating a Cookie

setcookie("user", "Admin", time() + 3600, "/");

Accessing a Cookie

echo $_COOKIE['user'];

Deleting a Cookie

setcookie("user", "", time() - 3600, "/");

Cookie Example

if (!isset($_COOKIE['visit'])) { setcookie("visit", "1", time() + 3600); echo "Welcome, first time visitor!"; } else { echo "Welcome back!"; }

Sessions in PHP

What is a Session?

A session stores user data on the server and assigns a unique session ID to the user. This ID is usually stored in a cookie.


Starting a Session

session_start();

Creating Session Variables

$_SESSION['username'] = "Admin"; $_SESSION['role'] = "User";

Accessing Session Variables

echo $_SESSION['username'];

Destroying a Session

session_start(); session_unset(); session_destroy();

Complete Session Example

session_start(); if (!isset($_SESSION['login'])) { $_SESSION['login'] = true; echo "Session started"; } else { echo "Session already exists"; }

Cookies vs Sessions

FeatureCookiesSessions
StorageBrowserServer
SecurityLess secureMore secure
Data SizeSmall (4KB)Large
LifetimeSet by expiryUntil session ends
PerformanceFasterSlightly slower

Security Best Practices

  • Use HTTPS for cookies

  • Set HttpOnly and Secure flags

  • Regenerate session ID after login

  • Destroy sessions on logout

  • Avoid storing sensitive data in cookies


Secure Cookie Example

setcookie( "user", "Admin", time() + 3600, "/", "", true, true );

Common Use Cases

  • Login systems

  • Shopping carts

  • User preferences

  • Authentication and authorization


Conclusion

Cookies and sessions are essential for maintaining user state in PHP applications. Cookies are client-side, while sessions are server-side, making sessions more secure for sensitive data.


πŸ”’ Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes