Cookies in PHP

free php tutorials, php classes, php utilities, free tools

What is a Cookie?

The main purpose of cookie to identify a user. A Cookie is a small pieces of information that are stored in your web browser. Cookies are a huge hype these days, both for programmers and users, Users can store their username, email addresses and other important information. And programmers can easily collect information about users.

How to Create a Cookie
The setcookie() function is used to create a cookie.

  • Name : Name of the cookie.
  • Value : value of cookie variable name
  • Expire : The specified time when a cookie will be expired.
setcookie(name, value, expire, );

<?
setcookie ("cookie", "programmersbank.com", time()+36000);
//makes a variable $cookie with a value of "programmersbank.com"
?>
<html>
<body>
<p>
This cookie has a value programmersbank, and this cookie will expire after 10 hours
</p>
</body>
</html>

How to Retrieve a Cookie Value
When a cookie is set, PHP uses the cookie name as a variable.
To access a cookie you just refer to the cookie name as a variable.

<?php
if (!isset($_COOKIE["name"])) {
setcookie("name", $_POST["name"]);
setcookie("visits", 1);
echo "Hello $_POST[name]. <br />";
echo "It appears that this is your first visit!";
} else {
setcookie("visits", ++$_COOKIE["visits"]);
echo "Welcome back, $_COOKIE[name]. <br />";
echo "You have visited us $_COOKIE[visits] times!";
}
?>

Bookmark This Page