PHP - Cookies
Cookies are text files stored on the client computer and they are used for tracking purpose. PHP transparently supports HTTP cookies. There are three steps involved in identifying returning users:
- Server script sends a set of cookies to the browser. For example name, age, or id etc.
- Browser stores this information on local machine for future use.
- When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.
Create Cookies With PHP
A cookie is created with the PHP setcookie() function. It defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from the script. This requires to place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST array.
Syntax
setcookie(name, value, expires, path, domain, secure, httponly) //alternative signature available as of PHP 7.3.0 setcookie(name, value, options)
Parameters
name |
Required. Specify the name of the cookie. |
value |
Optional. Specify the value of the cookie. This value is stored on the clients computer. This value can be retrieved through $_COOKIE['cookiename']. |
expires |
Optional. Specify the time the cookie expires. This is a Unix timestamp which is in number of seconds since the epoch. For example: time()+60*60*24*30 will set the cookie to expire in 30 days. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes). Default is 0. |
path |
Optional. Specify the server path of the cookie. If set to '/', the cookie will be available within the entire domain. If set to '/php/', the cookie will only be available within the /php/ directory and all sub-directories of php. The default value is the current directory that the cookie is being set in. |
domain |
Optional. Specify the (sub)domain name that the cookie is available to. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain |
secure |
Optional. Specify whether or not the cookie should only be transmitted over a secure HTTPS connection from the client. When set to true, the cookie will only be set if a secure connection exists. Default is false. |
httponly |
Optional. If set to true the cookie will be made accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages, such as JavaScript). This setting can help to reduce identity theft through XSS attacks. Default is false. |
options |
|
Return Value
If output exists prior to calling this function, setcookie() will fail and return false. If setcookie() successfully runs, it will return true. This does not indicate whether the user accepted the cookie.
Send Cookies
The example below shows how to send the set cookies request using PHP script.
<!DOCTYPE html> <?php //expire at the end of the session setcookie("name", "John Smith"); //expire in 1 hour setcookie("age", 27, time()+3600); //expires in 1 hour- this cookie will be available //within the entire domain if set through secure //HTTPS connection from the client setcookie("hobbies", "painting", time()+3600, "/", "", 1); ?> <html> <head><title>Setting Cookies</title></head> <body> <?php echo "Set Cookies"; ?> </body> </html>
Access Cookies
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST. $_COOKIE['cookiename'] can be used to retrieve the cookie value. Consider the example below:
<!DOCTYPE html> <?php //expire in 1 hour setcookie("TestCookie", "CookieValue", time()+3600); ?> <html> <head><title>Accessing Cookies</title></head> <body> <?php if(!isset($_COOKIE["TestCookie"])) { echo "This cookie is not set."; } else { echo "Value is: ".$_COOKIE['TestCookie']; } ?> </body> </html>
Delete Cookies
To delete a cookie, the expiration date can be set in the past using setcookie() function. This will trigger the removal mechanism in the browser.
<!DOCTYPE html> <?php //setting the expiration date in past 1 hour will //trigger the removal mechanism in the browser setcookie("TestCookie", "CookieValue", time()-3600); ?> <html> <head><title>Deleting Cookies</title></head> <body> <?php echo "Deleting Cookies"; ?> </body> </html>
Modify Cookies
To modify a cookie, just set the cookie again using the setcookie() function.
<!DOCTYPE html> <?php //this will modify the expiration time to 2 hours setcookie("TestCookie", "CookieValue", time()+7200); ?> <html> <head><title>Modifying Cookies</title></head> <body> <?php echo "Modifying Cookies"; ?> </body> </html>
Check if Cookies are Enabled
The following example can be used to check whether cookies are enabled or not. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
<!DOCTYPE html> <?php //this will modify the expiration //time to 2 hours setcookie("TestCookie", "CookieValue", time()+7200, "/"); ?> <html> <head><title>Modifying Cookies</title></head> <body> <?php if(count($_COOKIE) > 0) { echo "Cookies are enabled."; //codes } else { echo "Cookies are disabled."; //codes } ?> </body> </html>
setcookie() and Arrays
The array cookies can be set by using array notation in the cookie name. Consider the example below:
<!DOCTYPE html> <?php //set cookie array setcookie("arr[three]", "cookiethree"); setcookie("arr[two]", "cookietwo"); setcookie("arr[one]", "cookieone"); ?> <html> <head><title>Modifying Cookies</title></head> <body> <?php //after the page reloads, displaying them if (isset($_COOKIE['arr'])) { foreach ($_COOKIE['arr'] as $name => $value) { $name = htmlspecialchars($name); $value = htmlspecialchars($value); echo "$name : $value <br>\n"; } } ?> </body> </html>
The output of the above code will be:
three : cookiethree two : cookietwo one : cookieone
Note: setrawcookie() is exactly the same as setcookie() except that the cookie value will not be automatically urlencoded when sent to the browser.