Setting Cookies
A cookie is basically a text file located on the visitor's computer used for various purposes by the website.
For instance, a cookie can hold your username for that website, and this is the example that this tutorial will be building on.
A cookie can be easily set using PHP's setcookie() function:
| bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]]) |
The above shows how setcookie() should be used. First, you start the function by typing setcookie( , then you state the name of the cookie, the cookie's value and expiration date.
Keep in mind that anything in the [] square brackets is optional, but it is always a good practice to include the expiration date, and you will obviously want a cookie value (unless the cookie is being deleted).
Ready to set a cookie?
| <?php$name = "Mike"; setcookie("username",$name,time()+3600);?> |
The code above sets a cookie called "username" with a value "Mike", which will expire in 3600 seconds (or 1 hour).
Now that we have a cookie set, the logical thing to do would be to "read" it.
Since the cookie is named "username", all we have to do to print out the value of the cookie is:
| <?phpecho $_COOKIE["username"];?> |
Alternatively, you can use $name = $_COOKIE["username"];, this way you can do anything you wish with $name.
As you can see, reading cookies is extremely easy.
The next page will tell you how to delete cookies and how to avoid common mistakes.