Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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 not ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page