Php Cookies


The Cookies are text files stored on the client computer and they are kept for user tracking purposes. PHP transparently supports HTTP cookies.

Create Cookies With PHP

Php provided setcookie() function to set a cookie. This function requires up to six arguments and should be called before the tag. for each cookie, this function has to be called separately.

Syntax

setcookie(name, value, expire, path, domain, security);

Name:

This sets the name of the cookie and is put away in a situation variable called HTTP_COOKIE_VARS. This variable is utilized while getting to cookies.

Value:

This sets the estimation of the named variable and is the substance that you really need to store.

Expiry:

This determines a future time in seconds since 00:00:00 GMT on first Jan 1970. After this time cookie will get distant. In the event that this parameter isn't set, at that point, the cookie will consequently lapse when the web browser is closed.

Path:

This determines the indexes for which the treat is legitimate. A solitary forward cut character allows the cookie to be substantial for all indexes.

Domain:

This can be utilized to indicate the space in exceptionally enormous areas and must contain at any rate two periods to be legitimate. all cookies are just substantial for the host and area which made them.

Security:

This can be set to 1 to indicate that the treat should just be sent by secure transmission utilizing HTTPS in any case set to 0 which means the cookie can be sent by normal HTTP.

Example

<?php
   setcookie("name", "John doe", time()+3600, "/","", 0);
   setcookie("age", "36", time()+3600, "/", "",  0);
?>
<html>
  <body>
      <?php echo "Set Cookies"; ?>
   </body>   
</html>

Retrieve a Cookie

you can retrieve cookies using the below example.

<html>
<body>

<?php
if(!isset($_COOKIE['name'])) {
    echo "<p>Welcome " .$_COOKIE['name']."</p>";
} else {
    echo "<p>Sorry ... Not recognized</p>";
}
?>

</body>
</html>
 

Delete a Cookie

Example

In here below example, you can delete the cookie using the specific cookie name.

<?php
setcookie("name", "", time() - 3600);
?>