Cookies in PHP are small files stored on the user’s browser to remember information between different page requests. They are typically used for:
- User login sessions
- Remembering user preferences
- Tracking user activity
How Cookies Work:
-
The server sends a cookie using PHP.
-
The browser stores it.
-
On every subsequent request, the browser sends the cookie back to the server.
How to Set a Cookie in PHP:
login.php
// Set a cookie
setcookie("user", "John", time() + 3600); // valid for 1 hour
user
= Cookie name"John"
= Cookie valuetime() + 3600
= Expiration time (current time + 1 hour)
How to Retrieve a Cookie:
echo $_COOKIE['user']; // Outputs: John