PHP Cookies

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


What are Cookies?

Cookie is a piece of information that is stored as text files on the visitor's browser/computer. This allows the website server to keep track of what a visitor is doing during their visit (or even across multiple visits).

As an example to this is Amazon.com: do you notice that if you visit Amazon.com, Amazon keeps track of the click you have made. Even if you come to the site after sometime, it knows that you had visited earlier and would show you your earlier visits. This happens because Amazon.com stores cookies on your computer.

Sometimes cookies is being used by advertisers to track an individual's browsing habits. Any decent anti-spyware program can prevent that kind of thing, however, and cookies are a useful and necessary mechanism for such things as personalized sites (where you first log in, and are then presented your personalized version of the site), shopping carts etc.

Creating PHP Cookie

PHP has support for cookies. A cookie is sent by using setcookie( ) function. Here's an example:


<?php
setcookie 
("examplecookie""the cookie text");
?>
<html>
<head>
</head>
<body>
</body>
</html>
?>

Here you are creating a cookie: "examplecookie" that stores "the cookie text". Also, note that cookie is being created before sending any HTML to the browser.

Reading PHP cookie

So, to read our cookie, we would simply reference it's variable name like this:


<?php
print "our cookie says $examplecookie";
?>

This would show up on the page as:
<?php
our cookie says the cookie text
?>

Deleting PHP cookie

When cookies are created, they are by default deleted when the user closes his browser. Expiration can be set by using time as follows:


<?php
setcookie 
("examplecookie""the cookie text"time( ) + 3600);
?>
<html>
<head>
</head>
<body>
</body>
</html>
?>

Above example shows that cookie would expire 3600 sec (or 1 hour) from now.

You can delete a cookie forcefully by using negative time as follows:


<?php
setcookie 
("examplecookie"""time( ) - 1);
?>

As explained earlier, always remember that the setcookie( ) function has to come before anything else on the web page.





Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.