Cookies in PHP

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Cookies
Cookies let you store data in user's browser and access that data when user visits website again. As cookies are stored in browser thus can be very helpful identifying users even if the browser is terminated in between.
You must have noticed remember me option when you log into any site and once you terminate the browser and open that site again after that, you are still logged in. This is done using Cookies.
You can create or set cookies using set_cookie() function.

set_cookie(string $name[, string $value[,int $expire[,string $path
          [,string $domain[,bool $secure[,bool $httponly]]]]]])

Note: The [ denotes that these parameters may or may not be passed. This is just denotation not the part of syntax of function. Here we can only pass $name or $name,$value and this function won't throw any error.

set_cookie() must be called before sending any data to the browser as cookies are set through HTTP header, thus this won't work if any data is sent to the browser.
$_COOKIE
It is an array of all the cookies that are available to that domain and the path. We can access any cookie with $_COOKIE['name'].
Cookies can also be accessed using $_REQUEST array as it is an array containig all the elements of $_GET, $_POST and $_COOKIE.

<?php
setcookie("first_cookie", "User name");

setcookie("second_cookie", "User address", time()+3600); 
     // Valid or one hour from current time

if(isset($_COOKIE['first_cookie'])&&isset($_COOKIE['second_cookie'])){

    echo $_COOKIE['first_cookie']."\n".$_COOKIE['second_cookie'];
   }

?>


Output
User name User address

You will not get any output for the first time. You will need to reload as $_COOKIE variable is populated before and cookies are set.
Your Cookies will be there as long as cookies are not cleared by the user or cookies are expired. To avoid overwriting of always check if a cookie is already present. The above code will always overwrite cookies.

Keep in mind that as cookies are stored in local storage of user, it can be manipulated and thus you need to be cautious.

Login to Track Your Progress