Hudzilla.org - the homepage of Paul Hudson
Contents > Cookies and Sessions Wish List | Report Bug | About Me ]

10.2     Using cookies: setcookie()

This is NOT the latest copy of this book; click here for the latest version.

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, int secure]]]]])

Taking the example of sorting a messageboard index, a cookie would need to be placed that holds the user's preference on message sorting - whether they want it newest first, oldest first, or sorted alphabetically. Take a look at this piece of code:

<?php
    
if (!isset($_COOKIE['Ordering'])) {
        
setcookie("Ordering", $_POST['ChangeOrdering'], time() + 31536000);
    }
?>

<FORM METHOD="POST" ACTION="mbprefs.php"> Reorder messages:
<SELECT NAME="ChangeOrdering">
<OPTION VALUE="DateAdded ASC">Oldest first
<OPTION VALUE="DateAdded DESC">Newest first
<OPTION VALUE="Title ASC">By Title, A-Z
<OPTION VALUE="Title DESC">By Title, Z-A
</SELECT>
<INPUT TYPE="SUBMIT" VALUE=" Save Settings ">
</FORM>

The script can be split up into two distinct parts - first we check whether a cookie is set, and, if not, we use the setcookie() function to set it. Then we output a form allowing visitors to select how they'd like their ordering set.

The setcookie() call needs to be before the HTML form because of the way the web works. The explanation requires a little knowledge of how HTTP works and is quite important if you want to understand how cookies work, but never fear - I will try to keep it as simple as possible!

HTTP operates by sending all "header" information before it sends "body" information. In the header, it sends things like server type (e.g. "Apache"), page size (e.g. "29019 bytes"), and other important data. In the body, it sends the actual HTML you see on the screen. HTTP works in such a way that header data cannot come after body data - you must send all your header data before you send any body data at all.

Cookies come into the category of header data - when you place a cookie using setcookie(), your web server adds a line in your header data for that cookie. If you try and send a cookie after you have started sending HTML, PHP will flag up serious errors and the cookie will not get placed.

There are two ways to correct this:

  • Put your cookies near the top of your page. By sending them before you send any body data, you avoid the problem entirely.

  • Enable output buffering in PHP. This allows you to send header information such as cookies wherever you like - even after (or in the middle of) body data. Output buffering is covered in depth in its own chapter.

The setcookie() function itself takes three main parameters: the name of the cookie, the value of the cookie, and the date the cookie should expire.

Author's Note: One important thing to remember about cookies is that they are sent to the server each time a user visits a page. So, if you set a cookie in a script, it does not become available until your user visits the next page (or hits refresh) - this often confuses people who are desperately hunting for a bug.

In the example code, setcookie() sets a cookie called "Ordering" to the value set in the form from the drop down SELECT box, and it uses time() + 31536000 as its third parameter - this is equal to the current time in seconds plus the number of seconds in a year, which means the cookie is set to expire one year from the time it was set.

Once set, the Ordering cookie will be sent with every subsequent page request, and PHP will make it available in $_COOKIE. Note that users can clear their cookies manually, either by using a special option in their web browser or just by deleting files. It is also important to note that cookies are sent from your visitor to you when the page is requested - if you set the cookie during the PHP script that is requested, it will not have been sent with the request, which means it will not be in $_COOKIE - this is what is meant by "every subsequent page request"!

The last three parameters of the setcookie() function allow you to restrict when it's sent, which gives you a little more control. They aren't used often, but, in case you were interested, here's how they work:

  • Parameter four ("path") allows you to set a directory in which the cookie is active. By default, this is "/" (active for the entire site), but you could set it to "/messageboards/" to have the cookie only available in that directory and its subdirectories.

  • Parameter five ("domain") allows you to set a subdomain in which the cookie is active. For example, specifying "mail.yoursite.com" will make the cookie available there but not on www.yoursite.com. Use ".yoursite.com" to make the cookie available everywhere.

  • Parameter six ("secure") lets you specify whether the cookie must only be sent through a HTTPS connection or not. The default, "0", has the cookie sent across both HTTPS and HTTP, but you can set it to 1 to force HTTPS only.





<< 10.1.3 Choosing the appropriate option   10.3 Using sessions >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
A PHP troubled User - 05 Dec 2008

i'm having trouble with setcookie(); it seems that when i send the information, it doesn't recognize the info until i refresh the page?

A PHP User - 05 Dec 2008

I have problem to expire the cookie in IE.
i wrote the following to expire cookie but it didn't work

setcookie("username", "", time()-1000, "/");
setcookie("password", "", time()-1000, "/");

Also i tried with the code :
$Browsertype = $_SERVER['HTTP_USER_AGENT'];
$Parts = explode(" ",$Browsertype);
$MSIE = array_search("MSIE",$Parts);

if($MSIE)
{
setcookie("username", "", time()+2000,"/");
setcookie("password", "", time()+2000,"/");
}

but still not working, although it works in FireFox
did any one have a solution to expire cookie in IE?

A PHP User - 05 Dec 2008

yeah IE6 doesn't recognize cookies, it only works in the localhost but not in the actual webserver ....

A PHP User - 05 Dec 2008

what about the IE6 XP bug ? I cant get my IE6 to set cookies... :( Big problem

A PHP User - 05 Dec 2008

dddd

A PHP User - 05 Dec 2008

some ommissions:


what happens if you don't specify a value for expire?

the cookie will expire when the browser closes.


how do you destroy the cookie?

use setcookie again, with the same parameters as when you created it, except with value = "" and expire = some time in the past.



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is one plus one?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow