Cookies in PHP, is a client management technique and are text file used to store small amount of data on users computer(client). It is mostly used to store user preferences or personalization. Because it is stored in users computer, it is not secure. Hence information like login and account should not be saved in cookies.

PHP uses HTTP Header to send cookies to user browsers, and it save its. and with each request it send cookies to server.

Syntax

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

name parameter is required. All other parameters are optional.

nameIt is key used to access value of given cookie
valueIt is value of the key
expireIt is the time of cookie to stay in user browser, Once the expire time is reached, browser automatically deletes the cookie
pathWhere cookie is stored
domainDomain for cookie access
securityUsed to set cookies uses HTTPS or not.

Example

<?php
 setcookie("user", "vasu", time() + (4 * 24), "/");
?>

Check cookie is set or not

<?php
setcookie("user", "vasu", time() + (4 * 24), "/");

 if (isset($_COOKIE["user"])) 
      echo "User Name is  " . $_COOKIE["user"]; 
 else
      echo "Cookie is not created or Set"; 

?>

Get or Access cookie value

<?php
setcookie("user", "vasu", time() + (4 * 24), "/");

echo $_COOKIE["user"];
?>

Deleting Cookies

Browser deletes the cookie as per time set in Expiry parameter of setcookie(). But cookie can also be deleted by setting past time in setcookie() function.

<?php
setcookie("user", "vasu", time() + (4 * 24), "/"); // creating cookie

echo $_COOKIE["user"]; // get cookie value
 setcookie("user", "", time() - 60);  // Deletes cookies
 if (isset($_COOKIE["user"]))  // check cookie is set or not
        echo "User Name is  " . $_COOKIE["user"]; 

?>

If expiry time is not specified in cookie method, browser will delete cookie, when it is closed.