Saturday 24 February 2018

Cookie in PHP

Cookies are small text files stored on the client computer.
Cookies are stored in  browser and it can store limit amount of data So it is less secure.
It is used to identify the user.
Using PHP, we can create and retrieve cookie values.
It  can store data up to  4kb [4096bytes].

Note: PHP Cookie must be used before <html> tag.
Create or set Cookies (setcookie())
setcookie() function is used to create or set cookies.
Once cookie is set, you can access it by $_COOKIE super global variable.
isset() function is to find out if the cookie is set:

Syntax

setcookie (name, value, expire, path, domain, secure, httponly);
Where name parameter is required and all other parameters are optional.


Retrieve or get cookies($_COOKIE  )
$_COOKIE  is a super global variable  which is used to get or retrieve  cookies
Syntax:
 $value=$_COOKIE["CookieName"];

Example:
<!DOCTYPE html>
<?php
$cookie_name = "admin";
$cookie_value = "dipak";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
     echo "Cookie named '" . $cookie_name . "' is not set";
}
else {
     echo "Cookie '" . $cookie_name . "' is set<br>";
     echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p >Note: Please reload the page to see the new value of the cookie. </p>
</body>
</html>
Output:
Cookie 'admin' is set
Value is: Dipak
Please reload the page to see the new value of the cookie

Delete a Cookie
To delete a cookie,use the setcookie() function with an expiration date in past.
Syntax:
setcookie ("CookieName", "", time() - 3600); // set the expiration date to one hour ago 
 Example:
<?php
// set the expiration date to one hour ago
setcookie ("admin", "", time () - 3600);
?>
<!DOCTYPE html>
<html>
<body>
<?php
echo "Cookie 'admin' is deleted.";
?>
<body>
<html>
Output:
Cookie 'admin' is deleted


No comments:

Post a Comment

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...