This comprehensive guide will help you understand the fundamental concepts of PHP Sessions and Cookies with examples, workflows, and practical applications.
A cookie is a small file (up to 4KB) stored on the client’s device by the web server. It helps maintain state information about the user across different pages or sessions. Cookies are sent back to the server with every subsequent request.
www.google.com
cannot be accessed by www.yahoo.com
.Temporary Internet Files
for Internet Explorer.The setcookie()
function is used to create a cookie.
name
(mandatory): Name of the cookie.value
(mandatory): Value of the cookie.expiry_time
(optional): Expiration time (e.g., time() + 3600
for 1 hour).path
(optional): Path where the cookie is available (e.g., /
for the entire domain).domain
(optional): Domain or subdomain access restrictions.secure
(optional): Restrict cookies to HTTPS when true
.httponly
(optional): Prevent access by JavaScript when true
.The following example creates a cookie that stores the username and expires in 1 minute:
To retrieve cookies, use the $_COOKIE
superglobal array.
To delete a cookie, set its expiration time to a past time.
A session is a global variable stored on the server. Each session has a unique ID shared with the client via a cookie or URL. Sessions are more secure than cookies because the data is stored on the server, not the client’s device.
Use the session_start()
function to initiate a session.
Access session variables using the $_SESSION
superglobal array.
To remove session data:
Destroy Entire Session:
Unset a Specific Session Variable:
Sessions are commonly used for login systems:
Feature | Cookies | Sessions |
---|---|---|
Storage | Client-side | Server-side |
Security | Less secure (can be tampered with) | More secure (data stored on the server) |
Size Limit | 4KB | Virtually unlimited |
Lifetime | Persistent until expiry or cleared | Ends with browser session (or manual) |
Data Sharing | Stored in $_COOKIE | Stored in $_SESSION |
Use Cases | Personalization, basic tracking | Authentication, sensitive information |
Both cookies and sessions are integral to web development for maintaining user state and enhancing interactivity.
By understanding their differences and use cases, you can design robust and user-friendly web applications.