A cookie is commonly used to identify a user. It is a small file placed on the user’s computer by the server. Each time the same computer requests a page through a browser, it sends the cookie along with the request. With PHP, you can create and retrieve cookie values.
A cookie is created using the setcookie()
function.
setcookie(name, value, expire, path, domain, secure, httponly); |
Only the name
parameter is required when creating a cookie; all other parameters are optional.
The following example creates a cookie named “user” with the value “John Doe,” which will expire after 30 days (86400 seconds * 30). The “/” specifies that the cookie is accessible across the entire website; otherwise, you can choose a specific directory.
We then retrieve the value of the “user” cookie using the global $_COOKIE
variable and use the isset()
function to check if the cookie is set.
<?php $cookie_name = “user”; $cookie_value = “John Doe”; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”); // 86400 = 1 day ?> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo “Cookie named ‘” . $cookie_name . “‘ is not set!”; } else { echo “Cookie ‘” . $cookie_name . “‘ is set!<br>”; echo “Value is: “ . $_COOKIE[$cookie_name]; } ?> </body> </html> |
Note: The setcookie() function must be called before the <html> tag. |
Note: The value of the cookie is automatically URL-encoded when sent and automatically decoded when received. To prevent URL encoding, use setrawcookie()
instead.
To modify a cookie, simply reset it using the setcookie()
function.
<?php $cookie_name = “user”; $cookie_value = “Alex Porter”; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), “/”); ?> <html> <body> <?php if(!isset($_COOKIE[$cookie_name])) { echo “Cookie named ‘” . $cookie_name . “‘ is not set!”; } else { echo “Cookie ‘” . $cookie_name . “‘ is set!<br>”; echo “Value is: “ . $_COOKIE[$cookie_name]; } ?> </body> </html> |
To delete a cookie, use the setcookie()
function with an expiration date set in the past.
<?php // set the expiration date to one hour ago setcookie(“user”, “”, time() – 3600); ?> <html> <body> <?php echo “Cookie ‘user’ is deleted.”; ?> </body> </html> |
The following example demonstrates a script that checks if cookies are enabled. It first attempts to create a test cookie using the setcookie()
function, then counts the number of elements in the $_COOKIE
array variable.
<?php setcookie(“test_cookie”, “test”, time() + 3600, ‘/’); ?> <html> <body> <?php if(count($_COOKIE) > 0) { echo “Cookies are enabled.”; } else { echo “Cookies are disabled.”; } ?> </body> </html> |