A cookie is a message given to a Web browser by a Web server. The browser stores the message in a small text file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, the cookie is sent back to the server too.
There are a wide variety of things you can do with cookies. They are used to store information about user, visited pages, poll results and etc. The main purpose of cookies is to identify users and possibly prepare customized Web pages for them.
Normally cookies are used only to store small amounts of data. Websites can read the values from the cookies and use the information as desired. In addition to the information it stores, each cookie has a set of attributes that helps ensure the browser sends the correct cookie when a request to a server is made.
Even though cookies are not harmful some people do not permit cookies due to concerns about their privacy. In this case you have to use Sessions.
PHP cookies can be set using the setcookie() function. The syntax is as follows:
setcookie(name[, value[, expire[, path[, domain[, security]]]]])
In the example below, we will create a cookie named "myCookie" and assign the value "PHP Tutorial" to it. We also specify that the cookie should expire after one hour and that the cookie is available for all pages within a Tutorials directory.
setcookie("myCookie", "PHP Tutorial", time()+3600, "/tutorials");
There's one important item to mention about using cookies. Because of the way cookies work within HTTP, it's important that you send all cookies before any output from your script. This requires that you place calls to this function before any output, including tags as well as any whitespace. If you don't, PHP will give you a warning and your cookies will not be sent.
Now the cookie is set and we need to retrieve the information. As mentioned above the name of each cookie sent by your server accessed with the superglobal array $_COOKIE. In the example below we retrieve the value of the cookie and print out its value on the screen.
echo "The cookie value is ".$_COOKIE['myCookie'];
This would show up on the page as: "myCookie value is PHP Tutorial".
By default, the cookies are set to be deleted when the browser is closed. We can override that default by setting a time for the cookie's expiration but there may be occasions when you need to delete a cookie before the user closes his browser, and before its expiration time arrives. To do so, you should assure that the expiration date is in the past. The example below demonstrates how to do it (setting expiration time 1 minute ago):
setcookie("myCookie", "", time()-60);
|Copyright © 2005-2007 www.WebCheatSheet.com All Rights Reserved.|