Sunday, 19 July 2020

Cookies PHP


A cookies is a variable set on server normally used to identify a user.  A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. A cookie can only be read from the domain that it has been issued from.


Syntax 

setcookie(name, value, expire, path, domain, secure, httponly);


  1. Name: It is used to set the name of the cookie.
  2. Value: It is used to set the value of the cookie.
  3. Expire: It is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
  4. Path: It is used to specify the path on the server for which the cookie will be available.
  5. Domain: It is used to specify the domain for which the cookie is available.
  6. Security: It is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.

Set Cookie

<?php 
$cookie_name="username";
$cookie_value="Girfa";

setcookie($cookie_name, $cookie_value, time() + (86400 * 3), "/"); // 86400 = 1 day
?>


Read Cookie


<?php

if(isset($_COOKIE["UN"]))
     echo $_COOKIE["UN"];
else
    header("location:index.php");
?>

Delete Cookies

if (isset($_COOKIE['UType'])) 
{
   unset($_COOKIE['UType']); 
   setcookie('UType', null, -1, '/');

No comments:

Post a Comment