Cookies in PHP - Basic Cookie
(Page 2 of 4 )
Let's look at an example that uses a very basic cookie:
<?php if (!isset($_COOKIE["name"])) {
setcookie("name", $_POST["name"]); setcookie("visits", 1);
echo "Hello $_POST[name]. <br />"; echo "It appears that this is your first visit!";
} else { setcookie("visits", ++$_COOKIE["visits"]);
echo "Welcome back, $_COOKIE[name]. <br />"; echo "You have visited us $_COOKIE[visits] times!"; } ?> |
The two points of interest are $_COOKIE and setcookie.
Cookie information sent by the browser is accessed with $_COOKIE, a super global array containing cookie values keyed by name.
The setcookie function is used to assign a key/value pair to be sent back to the client. The client uses the new values to update its cookies if the information already exists. If the information doesn't exist, new cookies will be created.
Remember that cookie information is exchanged within HTTP headers; cookies must be sent before the script generates any output.
Next: Cookie Attributes >>
More Programming Basics Articles
More By bluephoenix