Cookies in PHP

Cookies in PHP


Posted in : PHP Posted on : January 6, 2011 at 5:25 PM Comments : [ 0 ]

This section contains the detail about Cookies in PHP.

Cookie Example

In this tutorial you will learn how to used Cookie in PHP web application. A cookie is a small file that the server embeds on the user's computer and cookie is often used to identify a user. The setcookie() function is used to set a cookie and setcookie() function must appear BEFORE the <html> tag. The example of cookie creation is:

Example:

<?php
setcookie("user", "Avanish", time()+3600);
if (isset($_COOKIE['user']))
echo "Welcome " . $_COOKIE['user'] . "!<br />";
else
echo "Not set your name!<br />";
?>

Output:

Welcome Avanish!

In this tutorial set user "Avanish"  and set expire time  one hour . Again used  isset() function that check "user" cookie. If isset return false then "user" cookie not exist and user can't access it. If isset() method return true the cookie exist and user access it. Cookies can also store other things such as your name, last visit, shopping cart contents, etc by using setcookie() method;

Example:

<?php
setcookie("user", "Avanish", time()+3600, "/php/tutorials", "www.roseindia.net");
if (isset($_COOKIE['user'])){
echo "Welcome " . $_COOKIE['user'] . "!<br />"; 
}
else{
echo "Not set your name, expire time, path and domain value in cookie.!<br />";
}
?>

Output:

Welcome Avanish!

If you want to set expiration time for the cookie the use setcookie() method. In this example we have set one hour expiration time for the cookie when cookie is creates after one hour cookie expire automatically.

Example:

<?php
$cookie_expire_time=time()+60*60*24*30;
setcookie("user", "Avanish", $expire);
if (isset($_COOKIE["user"])){
echo "Welcome " . $_COOKIE["user"] . "!<br />"; 
}
else{
echo "Not set your name, expiration time in cookie.!<br />";
}
?>

Output:

Welcome Avanish!

Now we can retrieve the cookie value.

Example:

<?php
setcookie("user", "Avanish", time()+3600);
if (isset($_COOKIE["user"])){
echo $_COOKIE["user"] . "<br />"; 
}
else{
echo "Not set your name.<br />";
}
?> 

Output:

Avanish

Cookies are deleted by calling the setcookie() function with the cookie name, a null for the value and an expiration date in the past. Once again the time() function can be used to calculate an expired date:

Example:

<?php
setcookie("user", "", time()-60);
if (isset($_COOKIE["user"])){
echo $_COOKIE["user"] . "<br />"; 
}
else{
echo "Cookie expire.<br />";
}
?>

Output:

Cookie expire.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics