Cookies are small pieces of data stored in the browser. PHP uses setcookie() to create cookies and $_COOKIE to access them.
- User Preferences: Remember language, theme, and display settings.
- Authentication: Store session identifiers or authentication tokens with appropriate security controls.
- Shopping Carts: Store small amounts of cart-related information or identifiers for server-side cart data.
- Analytics: Track website visits and user interactions, subject to applicable privacy requirements.
PHP Uses the setcookie() Function to Create Cookies
The setcookie() function sends a cookie to the browser through an HTTP response header.
Syntax:
setcookie(name, value, options);PHP 7.3 and later support an options array for configuring cookie attributes.
| Parameter | Description |
|---|---|
| name | Specifies the cookie name. |
| value | Specifies the cookie value. |
| expires | Defines the expiration time as a Unix timestamp. |
| path | Specifies the URL path where the cookie is available. |
| domain | Specifies the domain that can access the cookie. |
| secure | When true, sends the cookie only over HTTPS connections. |
| httponly | When true, prevents JavaScript from accessing the cookie. |
| samesite | Controls when the browser sends the cookie with cross-site requests. Accepts Lax, Strict, or None. |
Only the cookie name is required. Other parameters are optional, but explicitly setting appropriate security attributes is recommended.
PHP Sends Cookies to the Browser Through HTTP Headers
Cookies work through the exchange of HTTP response headers and subsequent requests.
- Setting Cookies: PHP uses setcookie() to send a Set-Cookie header to the browser.
- Storing Cookies: The browser stores the cookie according to its attributes and browser policies.
- Sending Cookies: The browser sends applicable cookies with subsequent HTTP requests.
- Reading Cookies: PHP accesses cookies received in the current request through the $_COOKIE superglobal array.
- Expiring Cookies: The browser stops sending a cookie after it expires.
- Deleting Cookies: PHP can request deletion by sending a cookie with an expiration time in the past.
Note: Call setcookie() before sending output to the browser because it modifies HTTP response headers. A newly set cookie is normally available through $_COOKIE only on a subsequent request.
PHP Creates and Reads Cookies Using setcookie() and $_COOKIE
The following example creates a cookie named Auction_Item and attempts to read its value using $_COOKIE.
Example: Create and Read a Cookie
<?php
setcookie("Auction_Item", "Luxury Car", [
'expires' => time() + (2 * 24 * 60 * 60),
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
if (isset($_COOKIE['Auction_Item'])) {
echo "Auction Item: " .
htmlspecialchars($_COOKIE['Auction_Item'], ENT_QUOTES, 'UTF-8');
} else {
echo "Cookie is not available in this request.";
}
?>
Output on the first request:
Cookie is not available in this request.Output on a subsequent request, if the browser accepts and sends the cookie:
Auction Item: Luxury Car- The setcookie() function creates a cookie named Auction_Item with the value Luxury Car.
- The expires option sets its expiration time to two days from the current time.
- The path option makes the cookie available across the website.
- The secure option restricts the cookie to HTTPS connections.
- The httponly option prevents client-side JavaScript from accessing the cookie.
- The isset() function checks whether the cookie value is available in the current request.
- The $_COOKIE array retrieves the cookie value, while htmlspecialchars() escapes special HTML characters before displaying it.
Note: For local development over HTTP, set secure to false or configure HTTPS.
PHP Deletes Cookies by Setting an Expiration Time in the Past
The setcookie() function can delete a cookie by setting its expiration time to a past timestamp. The deletion request should use the same path and domain attributes as the original cookie.
Example: Delete a Cookie
<?php
setcookie("Auction_Item", "", [
'expires' => time() - 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]);
echo "Cookie deletion requested.";
?>
Output:
Cookie deletion requested.- The setcookie() function sends an updated cookie with an empty value.
- The expires option sets its expiration time to one hour in the past.
- The browser processes the expiration instruction and removes the cookie.
- The cookie may remain available in the current request's $_COOKIE array until a subsequent request.
Note: If the original cookie used a specific domain or path, those attributes must match when deleting it.
PHP Cookies Support Preferences, Authentication, Shopping Carts, and Analytics
Cookies support several common web application features.
| Use Case | Description |
|---|---|
| User Preferences | Remembers settings such as language, theme, and display preferences. |
| Authentication | Stores session identifiers or authentication tokens with appropriate security controls. |
| Shopping Carts | Stores small amounts of cart information or an identifier linked to server-side cart data. |
| Analytics | Helps measure website visits and user interactions, subject to applicable privacy requirements. |
PHP Cookie Security Depends on Proper Configuration
- Avoid storing passwords, sensitive personal information, or confidential application data directly in cookies.
- Use secure and httponly where appropriate, and configure samesite according to the application's needs.
- Validate cookie values on the server because clients can modify them.
- Use HTTPS to protect cookies during transmission.