Cookies are small files stored on the user's device used to transfer information between the browser and server. PHP offers a built-in function setcookie() to create, modify, and delete cookies.
The setcookie() function is used to create a cookie by passing its name, value, and optional parameters.
For example, to create a cookie named "username" with the value "John":
setcookie("username", "John");
You can specify the cookie's expiration time using the expires parameter. The example below sets the cookie to expire in one day:
$expiry = time() + 24 * 60 * 60; // One day later
setcookie("username", "John", $expiry);
The path parameter restricts the cookie's valid path. By default, the cookie is available to the current directory and subdirectories. The following example sets the path to the root directory:
setcookie("username", "John", $expiry, "/");
The domain parameter limits the cookie's valid domain. By default, cookies are valid for the current domain and its subdomains. Example:
setcookie("username", "John", $expiry, "/", ".example.com");
The secure parameter ensures the cookie is sent only over HTTPS, enhancing security for sensitive data:
setcookie("username", "John", $expiry, "/", ".example.com", true);
PHP uses the superglobal $_COOKIE array to access cookies sent by the client. It is an associative array where keys are cookie names and values are cookie contents.
$username = $_COOKIE["username"];
echo "Welcome back, " . $username;
To check if a cookie exists, use the isset() function:
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
} else {
echo "Welcome guest";
}
To modify a cookie's value, call setcookie() again with the same cookie name and a new value:
setcookie("username", "Jane", $expiry, "/", ".example.com");
To delete a cookie, set its expiration time to a past timestamp:
setcookie("username", "", time() - 3600); // Expire immediately to delete cookie
Since cookies are stored on the user's device, their data can be vulnerable to theft. Only store necessary data, use the secure flag to transmit cookies over HTTPS, and encrypt sensitive information stored in cookies.
Each cookie is generally limited to about 4KB in size, varying by browser. Cookies exceeding this limit might be rejected.
Different browsers handle cookies differently, so ensure compatibility to provide a smooth user experience.
Using PHP's setcookie() function makes it simple to create, read, modify, and delete cookies. The $_COOKIE array provides easy access to cookie data. Always consider security and browser compatibility to maintain stable and safe web applications.