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:


<?php
setcookie("Name", "Peter", time()+3600);
?>
<html>
.....

Bellow example2:

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


<?php
$expire=time()+60*60*24*30;
setcookie("Name", "Peter", $expire);
?>
<html>
.....

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:

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

// A way to view all cookies
print_r($_COOKIE);
?>

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


<html>
<body>

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

</body>
</html>

How to Delete cookie?

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


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

About the Author

avatar