How to create cookie in php?

How to create Cookie in php?

What is the use of Cookie in php?

How to use Cookie in php?

Description about Cookie is bellow:

Cookie is a small file.Cookie is used to identify a user.
At a same time computer send requests a page with a browser, it will send the cookie too. With php,
you can both create and retrieve cookie values.

How to create Cookie?

The setcookie() function is used to set a cookie.
Note:The setcookie() function must appear BEFORE the <html> tag.

Syntex of Setcookie.

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

Bellow example:

I will create a cookie named “Name” and assign the value “Peter” to it.
I also specify that the cookie should expire after one hour:

setcookie("Name", "Peter", time()+3600);

Bellow example2:

We can also set the expiration time in cookie in Other way.

setcookie("Name", "Peter", $expire);

Above example expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value. :
below example,we retrieve the value of the cookie named “name” and display it:

// Print a cookie
echo $_COOKIE["Name"];

// A way to view all cookies

following example we use the isset() function to find if a cookie has been set:


if (isset($_COOKIE["Name"]))
echo "Welcome " . $_COOKIE["Name"] . "!<br>";
echo "Hello Friend!<br>";


How to Delete cookie?

If you want to delete cookie you should assure that the expiration date is in the past.

// set the expiration date to one hour ago
setcookie("Name", "", time()-3600);

About the Author