Using cookies

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>
<option value="DateAdded DESC">Newest first</option>
<option value="Title ASC">By Title, A-Z</option>
<option value="Title DESC">By Title, Z-A</option>
</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.

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Using sessions >>

Previous chapter: Choosing the appropriate option

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.