Cookies
What is Cookie?

Cookie is a txt file. That is send by webserver to webbrowser. This cookies file store on User’s computer. When user open any page in browser, then every time webserver send cookie too. In php we can also create cookies.

For create/delete cookie we use setcookie()  function.

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

Parameters
Name:- The name of the cookies.
Value:- The value of the cookies.
Expire:- The time when cookies will expires.
Path:- The path where cookies strone on the server.
Domain:- The domain that the cookie is available. Note:- setcookies function use before <html>  tag.

Example 1:- This PHP Script create cookie.

<?php
setcookie("user", "John", time()+60);
?>

user is the name of Cookie
John is the value of the Cookie
time()+60 is a time(1 Min.) after 1 Min. Cookie will delete from user’s computer.

Example 2:- This PHP Script print cookie value.

<?php
if(isset($_COOKIE["user"]))
{
echo $_COOKIE["user"];
}
?>

Example 3:- This PHP Script print all cookies.

<?php
print_r($_COOKIE);
?>

Example 4:- This PHP Script to delete Cookie Data.

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

Note:- Cookies is use in Remember me script in login section.

Cookies and Array

<?php
setcookie("myarray[0]","Sunday");
setcookie("myarray[1]","Monday");
setcookie("myarray[2]","Tuesday");
setcookie("myarray[3]","Wednesday");

foreach ($_COOKIE['myarray'] as $value) {
  echo "$value ";
  }
 
?>


Previous
Next