PHP $_COOKIE


Introduction

The superglobal $_COOKIE stores variables passed to current script along with HTTP request in the form of cookies.$HTTP_COOKIE_VARS also contains the same information, but is not a superglobal, and now been deprecated.

What is a cookie?

Cookies are text files stored by a server on the client computer and they are kept of use tracking purpose. PHP transparently supports HTTP cookies. Cookies are usually set in an HTTP header. JavaScript can also set a cookie directly on a browser.

Server script sends a set of cookies to the browser. It stores this information on local machine for future use. When next time browser sends any request to web server, it sends those cookies information to the server and server uses that information to identify the user.

PHP contains  setcookie function to create a cookie object to be sent to the client along with HTTP response.

setcookie

Syntax

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

parameters

  • Name − name of the cookie stored.
  • Value − This sets the value of the named variable.
  • Expiry − This specifes a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
  • Path − directories for which the cookie is valid.
  • Domain − specifies the domain name in very large domains.
  • Security − 1 for HTTPS. Default 0 for regular HTTP.

Cookie example

<?php
if (isset($_COOKIE['username']))
echo "<h2>Cookie name is already set with value: " . $_COOKIE['username'] . "</h2>";
else{
   setcookie("username", "Anil");
   echo "<h2>Cookie is now set </h2>";
?>

To retrieve cookies on subsequent visit of client

Example

<?php
$arr=$_COOKIE;
foreach ($arr as $key=>$val);
echo "<h2>$key=>$val </h2>";
?>

Output

Browser will display result similar to following

username=>Anil

To delete cookie set the cookie with a date that has already expired

Updated on: 21-Sep-2020

670 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements