Working with Cookies- Retrieval & Deletion
Posted by tutor | Posted in PHP Tutorial | Posted on 08-07-2010-05-2008
0
Retrieving Cookie
The built-in PHP variable $_COOKIE is used to retrieve a cookie value.
In the example below, we retrieve the value of the cookie named “username” and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["username"];
// A way to view all cookies
print_r($_COOKIE);
?>
We can also use the isset() function to find out if a cookie has been set:
<body>
<?php
if (isset($_COOKIE["username"]))
echo “Welcome ” . $_COOKIE["username"] . “!<br />”;
else
echo “Welcome Tutor!<br />”;
?>
</body>
</html>
Deleting Cookie
When deleting a cookie, its should have been expired ie you should assure that the expiration date is in the past.
<?php
// set the expiration date to one hour ago
setcookie(”username”, “”, time()-3600);
?>
Browsers not supporting Cookies
If a browser do not support cookies, you will have to use other methods to pass information from one page to another in your application. You may use the form method to pass the information in such a case.
The form below passes the user input to “main.php” when the user clicks on the “Submit” button:
<html>
<body>
<form action=”main.php” method=”post”>
Name: <input type=”text” name=”username” />
Address: <input type=”text” name=”address” />
<input type=”submit” />
</form>
</body>
</html>
Retrieve the values in the “main.php” file like this:
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You live at <?php echo $_POST["address"]; ?>.
</body>
</html>
