PHP Cookies
PHP Cookies Tutorial
Cookies are small pieces of data stored on the user’s browser. PHP can create, read, and delete cookies to track user activity, preferences, or login information.
1️⃣ Setting a Cookie
Parameters of setcookie()
| Parameter | Description |
|---|---|
name |
Name of the cookie |
value |
Value stored in the cookie |
expire |
Expiration time in seconds (time() + seconds) |
path |
Path on the server where cookie is available (/ = entire website) |
domain |
Domain that can access the cookie |
secure |
true if HTTPS only |
httponly |
true to prevent JavaScript access (more secure) |
✅ Must call setcookie() before any HTML output.
2️⃣ Accessing a Cookie
-
Use
$_COOKIE['name']to access the cookie value. -
Cookies are stored on the client-side, sent with each request.
3️⃣ Modifying a Cookie
To change a cookie, set it again with the same name and new value:
4️⃣ Deleting a Cookie
To delete a cookie, set its expiration time in the past:
5️⃣ Example: Complete Cookie Example
6️⃣ Key Points
-
Cookies are stored on the client browser.
-
Expire automatically after specified time.
-
Use
$_COOKIEto read cookie values. -
setcookie()must be called before any HTML output. -
Can store user preferences, login info, or tracking data.
