PHP Tutorials


PHP $_COOKIE
March 4, 2008, 12:59 am
Filed under: PHP

PHP $_COOKIE
This variable is often used to identify a user. This is stored on the user’s computer so that every user will be identified if who are they. You can create and get the value of a cookie.

setcookie() function

This function is used to create a cookie. This should appear before the <html> tag.

Syntax:

setcookie (name, value, expire, path, domain);


Example (create a cookie):

<?php
setcookie(“firstname”, “Bryan”, time()+7200);
?> //this should be written before the <html> tag

Here is an example on how to retrieve the value of a cookie:
<?php
echo $_COOKIE[“firstname”];
?>

isset() function
This can be used to check if a cookie has been set.

Example (using isset() function):
<html>
<body>
<?php
if (isset($_COOKIE[“firstname”]))
{
echo “You are “ . $_COOKIE[“firstname”];
}
else
{
echo “Please input your firstname”;
}
?>
</body>
</html>


You can view all cookies by this:

<?php
print_r($_COOKIE);
?>

You can delete a cookie by setting its expiration date in the past like this:
<?php
setcookie(“firstname”,””,time()-7200);
?>


No Comments Yet so far
Leave a comment



Leave a comment
Line and paragraph breaks automatic, e-mail address never displayed, HTML allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>