PHP Programming/cookies

From Wikibooks, open books for an open world
Jump to: navigation, search

Return to PHP.

Contents

Cookies [edit]

Cookies are small pieces of data stored as text on the client's computer. Normally cookies are used only to store small amounts of data. 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.

This lesson covers setting and retrieving data from cookies.

Setting a cookie [edit]

Setting a cookie is extremely easy with setcookie().

 setcookie("test", "PHP-Hypertext-Preprocessor", time()+60, "/location", 1);

Here the setcookie function is being called with four arguments (setcookie has 1 more optional argument, not used here). In the above code, the first argument is the cookie name, the second argument is the cookie contents and the third argument is the time after which the cookie should expire in seconds (time() returns current time in seconds, there time()+60 is one minute from now). The path, or location, element may be omitted, but it does allow you to easily set cookies for all pages within a directory, although using this is not generally recommended.

You should note that since cookies are sent with the HTTP headers the code has to be at the top of the page (Yes, even above the DOCTYPE declaration). Any other place will generate an error.

Retrieving cookie data [edit]

If a server has set a cookie on the user's computer, the user's browser sends it to the server each time a page loads. The name of each cookie sent by your server is stored in the superglobal array _COOKIE. So in the above example the cookie would be retrieved by calling $_COOKIE['test']. To access data in the cookie we use explode(). explode() turns a string into an array with a certain delimiter present in the string. That is why we used those dashes(- hyphens) in the cookie contents. So to retrieve and print out the full form of PHP from the cookie we use the code:

 $array = explode("-", $_COOKIE['test']); //retrieve contents of cookie  
 print("PHP stands for " . $array[0] . $array[1] . $array[2]); //display the content

Note: $_COOKIE was Introduced in 4.1.0. In earlier versions, use $HTTP_COOKIE_VARS.

Where are cookies used? [edit]

Cookies can be often used for:

  • user preferences
  • inventories
  • quiz or poll results
  • shopping carts
  • user authentication
  • remembering data over a longer period

You should never store unencrypted passwords in cookies as cookies can be easily read by the users.

You should never store critical data in cookies as cookies can be easily removed or modified by users.