Monday 12 March 2012

Cookies


  • Setcookie() defines a cookie to be sent along with the rest of the HTTP header.
  • If the cookie is successfully created it returns true else it returns false.
  • Like other header, cookies must be sent before any output from your script.

Syntax for setting the value

Bool setcookie(string name [, string value [, int expire [, string path [,string domain [, bool secure]]]]] )

  • All the argument except the name argument are optional. You may also replace an argument with an empty string (“”) in order to skip that argument. Because the expire argument is integer. It cannot be skipped with an empty string, use a zero(0) instead.
  • The following table explain each parameter of the setcookie() function.

Parameter
Description
Name
The name of the cookie.
Value
The value of the cookie. This value stored on the client computer. Do not store sensitive information.
Expire
The time the cookie expires. This is a unix timestamp so is in number of seconds since the aporch.
Path
The path on the server in which the cookie will be available on.
Domain
The domain that the cookie is available.
Secure
Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to true, the cookie will only be set if a secure.

  • Once the cookies have been set, they can be accesed on the next  page load with the $_COOKIE or $HTTP_COOKIE_VARS array.

NOTE : $_COOKIE became available in PHP 4.1.0 and $_HTTP_COOKIE_VARS has existed sinces PHP 3.

Example – create a cookie

<?php 
          setcookie("test","Hello World");
          setcookie("test","Hello World",time()+3000);
          echo "cookie created ";
?>

Example – read a cookie

<?php 
          echo $_COOKIE["test"]."<br/>";
          echo $HTTP_COOKIE_VARS["test"]."<br/>";
          print_r($_COOKIE);
?>

Example – delete a cookie

<?php 
          setcookie("test","Hello World",time()-3000);
?>

Posted By : Hemangi Zala

No comments:

Post a Comment