A cookie is object used to identify the user by his/her computer.
Each time the same computer access the page,
the cookie will also be retrieved if the expiry date has future value.
To create cookies with php, you need the name of the cookie, value of the cookie, and you need to set an expiration date.
Use setcookie() function to set your cookies.
or print $_COOKIE[] to read a cookie.
The following example creates a cookie named userName and assigns value Sayid Warsame that is set to expire in 3600 seconds or 1hr:
<?php
setcookie("userName","Sayid Warsame", time()+3600);
?>
The followin example sets a cookie named lastVisit and sets to expire in 30 days:
<?php
$thisMonth = time()+3600*60*60*24*30;
setcookie("lastVisit", date("G:i - m/d/y"), $thisMonth);
?>
We created two cookies that retain username and last visit.
Now we want retreive those cookies.
The following example checks if cookies exists and retreives if so.
<?php
$visitor="";
$guest="";
if (isset($_COOKIE["userName"]))
{
$visitor= "Welcome Back " . $_COOKIE["userName"] . "<br/>";
}
else
{
$guest= "Username cookie does not exist. <br/>";
}
if (isset($_COOKIE["lastVisit"]))
{
$visitor=$visitor."your last visit was " . $_COOKIE["lastVisit"] . "<br/>";
}
else
{
$guest=$guest."First time in this month. <br/>";
}
print "$visitor <br>$guest";
?>
In previous example, we manually provided the username to the browser.
In the following example, we will create a form to let site visitors set their own username.
<?php
if (isset($_POST['submit']))
{
setcookie("userName", "", time()-3600);
setcookie("userName",$userName=$_POST['userName'], time()+60*60*24);
print "You have set the cookie with value: ". $_COOKIE["userName"];
}
?>
<html>
<body>
<form name="setC" method="post" action="<?php echo($PHP_SELF); ?>">
Type a userName: <input type="text" size="25" name="userName">
<input type="submit" name="submit" value="submit">
</form>
</body<
</html>
On the bove example, we also reset the cookie to distroy the previous userName cookie before we attemp to new cookie.
Here is the statement that resets the cookie.
setcookie("userName", "", time()-3600);
We set cookie to 1 minute a go. That clears out the cookie.
|