Using Cookies

The setcookie() call needs to be before the HTML form because of the way the web works. 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 serious errors and the cookie will not get placed.

There are two ways to correct this:

  • Put your cookies at the top of your page. By sending them before you send anybody 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 the following 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. For example:

    setcookie("Name", $_POST['Name'], time() + 31536000);

Warning

Cookies are sent to the server each time a user visits a page. So, if you set a cookie in a script, it does ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.