Cookies are text files stored on the client computer. A cookie is often used to identify a user. They are kept of use tracking purpose. PHP transparently supports HTTP cookies. PHP cookies can be created by using the setcookie() function.
Server script sends a set of cookies to the browser. 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.
Validity of CookieValidity of the cookie depends upon following parameters:
- name: The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.
- value: The cookie value. It is associated with the cookie name.
- expire: The time after which the cookie should expire in seconds.
- path : Specifies the exact path on the domain that can use the cookies.
- domain: The domain that the cookie is available. If not domain is specified, the default value is the value of the domain in which cookie was created.
- security: Specifies whether the cookie will be sent via HTTPS. A value of 1 specifies that the cookie is sent over a secure connection but it doesn't mean that the cookie is secure. It's just a text file like every other cookie. A value of 0 denotes a standard HTTP transmission.
setcookie(name, value, expire, path, domain, secure);
Note: The setcookie() function must appear before the <html> tag.
Create and Set cookies: <?php $cookie_name = 'php_cookie'; $cookie_value = 'test_cookie_set_with_php'; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), '/'); ?>
Read a Cookie
In Php, you can read a cookie by using $_COOKIE. Once the cookies have been set, they can be accessed on the next page load.
Read Cookies: <?php if( isset($_COOKIE["name"])) echo "Welcome " .$_COOKIE["name"]."<br />"; else echo "Sorry...!!!! Cookies Not recognized"."<br />"; ?>
Delete a Cookie
In Php, to delete a cookie value, you may set the expiry time of the cookie in the past.
<?php setcookie( "name", "", time()- 60, "/","", 0); setcookie( "age", "", time()- 60, "/","", 0); ?> <html> <head> <title>Deleting Cookies in php</title> </head> <body> <?php echo "Deleted Cookies"; ?> </body> </html>