Open In App

How to use setcookie() function in PHP ?

A cookie is often a small file that is embedded by the server from which the user has visited or is getting a response. Each time the computer requests a page within a browser, it will send a cookie. Using PHP we can do both create and retrieve cookie values.

A variable is automatically created with the same name that is of the cookie. For example, if a cookie was sent with the name “client”, a variable of name “client” is automatically created containing the cookie i.e $client. Cookies are sent along with the HTTP headers. Like other headers, cookies should be sent before any output from your script.



Create Cookie: The setcookie() function is used to create a cookie. The setcookie() function defines a cookie to be sent along with other HTTP headers. The setcookie() function should be appeared before the <html> and <head> tag.

Syntax:



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

Parameters:

Returns:

 Example 1:        




<?php
  $value = 'Arecookiesset';
  
  setcookie("TestCookie", $value);
  setcookie("check","are cookies set")
  ?>
  <?php
  // Print an individual cookie
  // echo $_COOKIE["TestCookie"] ."\n";
  // echo $_COOKIE["check"] ."\n";
  
  // Another way to debug/test is to view all cookies
  print_r($_COOKIE);
?>

Output:

Array ( [TestCookie] => Arecookiesset [check] => are cookies set )

Example 2: In this example, we are deleting the cookie name “check”.




<?php
  $value = 'Arecookiesset';
  
  setcookie("TestCookie", $value);
  setcookie("check","are cookies set");
  //deleting the cookie of name check
  setcookie("check","",time()-3600);
  ?>
  <?php
  // Print an individual cookie
  // echo $_COOKIE["TestCookie"] ."\n";
  // echo $_COOKIE["check"] ."\n";
  
  // Another way to debug/test is to view all cookies
  print_r($_COOKIE);
?>

Output:

Array ( [TestCookie] => Arecookiesset )

Article Tags :