CodesJava

Easy learning with example program codes

PHP Cookies


PHP Cookies:

A cookie is a small piece of information that the server stores at client browser to recognize the user in future. A cookie is sent every time, the same client sends request to the server. PHP facilitates the features of both creating and retrieving cookie values.

To Create a Cookie:
PHP setcookie() function is used to create a cookie.
Syntax:
setcookie(name, value, expire, path, domain, secure, httponly);

  • Name: It is a required parameter and accepts a string value which represents the name of the cookie.
  • Value: It is an optional parameter and accepts a string value which represents the value of the respected cookie.
  • Expire: It is an optional parameter and accepts an int value which represents the expiration time of the cookie.
  • Path: It is an optional parameter and accepts a string value.
  • Domain: It is an optional parameter and accepts a string value.
  • Secure: It is an optional parameter and accepts a boolean value.
  • Httponly: It is an optional parameter and accepts a boolean value.

 

 

To Retrieve a Cookie:
PHP $_COOKIE is a global variable which is used to retrieve a cookie.

To Modify a Cookie:
PHP setcookie() function can be used to set the Cookies again, if any modification is needed.

To Delete a Cookie:
PHP setcookie() function with a past date and time as the value of the Expire parameter is used to delete a cookie.

To Check if Cookies are Enabled/ Disabled:
Counting the number of $_COOKIE array variables, is used to check if the Cookies are enabled or are disabled. If the Count is greater than 0, Cookies are enabled, else cookies are Disabled.

Example 1: Program to set and retrieve a cookie

<!DOCTYPE html>
<?php
$CookieName = "Client";
$CookieValue = "Dharmesh Donga";
setcookie($CookieName, $CookieValue)
?>
<html>
<body>
 
<?php
if(!isset($_COOKIE[$Cookie_Name])) {
     echo "Cookie named '" . $Cookie_Name . "' not found!";
} else {
     echo "Cookie " . $Cookie_Name . " is set!<br>";
     echo "Value of Cookie is: " . $_COOKIE[$Cookie_Name];
}
?>
 
</body>
</html>

Output

Cookie Client is set!
Value of Cookie is: Dharmesh Donga

Example 2: Program to delete a cookie

<!DOCTYPE html>
<?php
setcookie("Client", "", time() - 1800);
?>
<html>
<body>
 
<?php
echo "You deleted the Cookie 'Client'.";
?>
 
</body>
</html>

Output

You deleted the Cookie 'Client'.
Posted in PHP   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki