how to create cookies in php

What are the  Cookies -: Cookies are small files which are stored on a user’s computer.Cookies are store on user side in the computer. They are designed to hold a modest amount of data specific to a particular client and website and can be accessed either by the web server or the client computer.

how to create cookies

Cookie’s are often used to identify a user in the php. A cookie is a small file that are store on the browser window’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. In the php  you can  create and retrieve cookie values.

Create a cookies in php -: We can create easily in php using the function. We can create cookies in by using the setcookie() function for syntax of

setcookie (cookies_name,cookies_value) ;

In this syntax the setcookie() is the function of creating a cookies . For creating a cookies we take a example

<!DOCTYPE html>
$cookies_name = "user";
$cookies_value = "Vikram Singh";
setcookie($cookies_name, $cookies_value); // defining a name and value of cookies 

if(!isset($_COOKIE[$cookies_name])) {
     echo "Cookie named '" . $cookies_name . "' is not set!";
} else {
     echo "Cookie '" . $cookies_name . "' is set!<br>";
     echo "Value is: " . $_COOKIE[$cookies_name];

Output of this program

Cookie 'user' is set!
Value is: Vikram Singh


Time set cookie in php -: We know that the cookie are a small file that store user browser. We can set the small time in cookie using this syntax

setcookie("CookieName", "CookieValue", time()+1*60*60);//This cookies expiry in 1 hour  

setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/", "", 1);  


Delete cookies in php-: When we set the time in the cookies.After ending this time the cookies are automatically deleted. For example if we are giving one hour time for creating a cookies when we are creating a cookies then  after one hour cookies are deleted.Use this syntax for checking the cookies

setcookie("CookieName", "CookieValue", time()+1*60*60); //This cookies expiry in 1 hour


Leave a Comment