Google News
logo
PHP Cookies
PHP cookie is a small piece of information which is stored at client browser.  PHP transparently supports HTTP cookies. 

Cookie is created at server side and saved to client browser.  Each time when client sends request to the server, cookie is embedded with request. Such way, cookie can be received at the server side.

You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. 
PHP Cookies
Setting Cookies with PHP

PHP provided setcookie() function to set a cookie. This function requires upto six arguments and should be called before <html> tag.

Syntax

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

The parameters of the setcookie() function have the following :

Parameter Description
name The name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS.
value The value of the cookie. Do not store sensitive information since this value is stored on the user's computer.
expires The expiry date in UNIX timestamp format. After this time cookie will become inaccessible. The default value is 0.
path Specify the path on the server for which the cookie will be available. If set to /, the cookie will be available within the entire domain.
domain Specify the domain for which the cookie is available to e.g www.example.com.
secure This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
<?php
   setcookie("name", "V V Ramana Reddy", time()+3600, "/","", 0);
   setcookie("age", "27", time()+3600, "/", "",  0);
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP Cookies</title>
</head>
   
<body>

 <?php
	 echo "Set Cookie"
 ?>

</body>
</html>
Output :
Accessing Cookies with PHP

PHP provides many ways to access cookies. The PHP $_COOKIE or $HTTP_COOKIE_VARS superglobal variable is used to retrieve a cookie value. Following example will access all the cookies set in above example.

<!DOCTYPE html>
<html>
<head>
    <title>Accessing Cookies with PHP</title>
</head>
   
<body>

  <?php
	 echo $_COOKIE["name"]. "<br />";
	 echo $_COOKIE["age"]; 
  ?>

</body>
</html>
Output :

<!DOCTYPE html>
<html>
<head>
    <title>Accessing Cookies with PHP</title>
</head>
   
<body>

  <?php
	 if( isset($_COOKIE["name"]))
		echo "Welcome To : " . $_COOKIE["name"] . "<br />";
	 
	 else
		echo "Cookies Not recognized" . "<br />";
  ?>

</body>
</html>
Output :
Deleting Cookie with PHP

To delete a cookie, use the setcookie() function with an expiration date in the past:

<?php
   setcookie( "name", "", time()- 250, "/","", 0);
   setcookie( "age", "", time()- 250, "/","", 0);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Deleting Cookie with PHP</title>
</head>
   
<body>

  <?php
		echo "Cookie 'name' is deleted.";
  ?>

</body>
</html>