PHP Cookies

  • Share
  • CevherShare
  • Share

 

cookies are used to store the data in browser.

Cookies of the webpage should be created before the HTML tag.  Therfore setcookie(); function will be used first of the webpage.

1
2
3
<?php
setcookie(name, value, expire, path, domain);
?>

 

Here setcookie(); function will create  a cookie with name “tobby” , value as “tobby cook” and expires after 1 hour from the time of creation.

time()+3600 will makes the cookie to be expire in 1 hour i.e., 60 seconds * 60 minutes

1
2
3
4
5
<?php
setcookie("Tobby", "tobby cook", time()+3600);
?>
<html>
</html>

 

Display the cookies

The cookie “tobby” will store the value “tobby cook”. $_COOKIE[‘tobby’]; will display “tobby cook”.

1
2
3
<?php
echo $_COOKIE[‘tobby’];
?>

 

Check whether cookie is present or not

1
2
3
4
5
6
7
8
9
10
11
12
<?php
if(isset($_COOKIE[‘tobby’]))
{
echo “Cookie named Tobby already created”;
}
else
{
echo “Cookie named Tobby oesn’t exists2”;
}
?>

&nbsp;

 

Deleting the cookies

For cookie to be expire in one day – 86400 ( 60 seconds * 60 minutes *  24 hours)

time()+86400 or time()+60*60*24

For cookie to be expire in one month – 2592000 ( 60 seconds * 60 minutes *  24 hours * 30 days)

time()+2592000 or time()+60*60*24*30

When we need to delete the cookie before the browser closes, time () with negative value will be used.

1
2
3
4
5
<?php
setcookie("Tobby", "tobby cook", time()-1);
?>
<html>
</html>

 

prasad

About prasad

Prasad K has written 111 post in this blog.