Sunday, November 13, 2011

Cookies

A cookie is often used to identify a user.
The setcookie() function must appear BEFORE the <html> tag.
A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too.
With PHP, you can both create and retrieve cookie values.

SET Cookie:
setcookie(name, value, expire, path, domain);
------------------------------
<?php
setcookie ("user", "Alex Parter", time()+3600);      //cookie expire after an hour
?>
<html>
.....
------------------------------
<?php
$expire=time()+60*60*24*30;                 //set expire time to a month
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....
------------------------------

Get Cookie 
------------------------------
<?php
//check if cookie has been set
if (isset($_COOKIE["user"]))
    // get the cookie and print it
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>
------------------------------
Print all cookies
print_r($_COOKIE);
------------------------------

Delete a Cookie (set the expiration date of cookie in the past)
<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

No comments:

Post a Comment