PHP Cookies
In PHP, cookies are a way to store data on the client’s browser that can be used across multiple pages or sessions. They are typically used to remember user preferences, track sessions, or store small pieces of information.
Setting Cookies
To set a cookie in PHP, use the setcookie() function. This function must be called before any HTML output is sent to the browser.
Syntax:
php
setcookie(name, value, expire, path, domain, secure, httponly);
name: The name of the cookie.
value: The value of the cookie.
expire: The time the cookie expires (in UNIX timestamp format). If not set, the cookie will last until the end of the session.
path: The path on the server where the cookie will be available. Default is the current directory.
domain: The domain that the cookie is available to.
secure: If true, the cookie will only be sent over secure HTTPS connections.
httponly: If true, the cookie will only be accessible via HTTP(S) and not through JavaScript.
Example:
php
// Set a cookie named "user" with the value "John Doe" that expires in 1 hour
setcookie("user", "John Doe", time() + 3600, "/");
Accessing Cookies
To access a cookie’s value, use the $_COOKIE superglobal array.
Example:
php
if (isset($_COOKIE["user"])) {
echo "User: " . $_COOKIE["user"];
} else {
echo "Cookie 'user' is not set.";
}
Deleting Cookies
To delete a cookie, you can set its expiration date to a time in the past.
Example:
php
// Delete the cookie named "user"
setcookie("user", "", time() - 3600, "/");
Cookie Example
Here’s a complete example that demonstrates setting, accessing, and deleting cookies:
php
// Setting a cookie
setcookie("user", "John Doe", time() + 3600, "/");
// Check if the cookie is set and display its value
if (isset($_COOKIE["user"])) {
echo "User: " . $_COOKIE["user"];
} else {
echo "Cookie 'user' is not set.";
}
// To delete the cookie, uncomment the line below
// setcookie("user", "", time() - 3600, "/");
Security Considerations
Secure Flag: Always set the secure flag to true for cookies that contain sensitive information to ensure they are only sent over HTTPS connections.
HTTPOnly Flag: Use the httponly flag to prevent JavaScript from accessing the cookie, which helps protect against XSS attacks.
Data Size: Cookies are limited in size (typically 4KB), so they should only be used for small amounts of data.
Cookie Limitations
Size Limit: Most browsers limit the size of cookies to 4KB and the number of cookies per domain.
Path and Domain: Ensure that the path and domain parameters are set correctly so that the cookie is available where needed.