PHP Programing language

Cookies in PHP
Previous Home Next
adplus-dvertising

Cookies

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 the domain that can use the cookies.
  5.  
  6. 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.
  7. 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.
Syntax:
setcookie(name, value, expire, path, domain, secure);

Note: The setcookie() function must appear before the <html> tag.

Example:

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.

Example:

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>

Output:

Previous Home Next