PHP Cookies

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.

Setting a cookie

Syntax
setcookie(name, value, expire, path, domain);

Example

<?php 
    setcookie("key", "value", time()+60, "/", 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.

getting cookie data

If a server has set a cookie the 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.

<?php 
    echo $_COOKIE['key'];
    #Output: value
?>

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.

Submit an Idea
  Thank you for your valuable feedback.
Your E-mail (optional):
Select Option:
Description:
 
Feedback
Your Name / email address
Feedback as
Your feedback
close
Quickly sign in with:

Create a FATALWEB account here:

First name:

Last name:

E-mail address:

Join Fatalweb

Already have a fatalweb account? Log in here