PHP Programing language

Cookies in PHP
Previous Home Next


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 Cookie

Validity of the cookie depends upon following parameters:
  1. name: The cookie name. The name of each cookie sent is stored in the superglobal array $_COOKIE.
  2. value: The cookie value.It is associated with the cookie name.
  3. expire: The time after which the cookie should expire in seconds.
  4. path : Specifies the exact path on thedomain that can use the cookies.
  5. domain: The domain that the cookie is available. If not domain is specified, the default value is the value of thedomain in which cookie was created.
  6. security:Specifies whether the cookie will besent 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:


$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:

  if( isset($_COOKIE["name"]))
    echo "Welcome " .$_COOKIE["name"]."<br />";
    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.

setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);

<title>Deleting Cookies in php</title>
echo "Deleted Cookies";


Previous Home Next