PHP: Set or Create a Simple Browser Cookie with setcookie

Posted July 14, 2006 by Quinn McHenry in PHP programming

Last Updated on

Web applications overcome the lack of session support in the HTTP protocol primarily through the use of cookies. Transparent to the user and simple for the web developer, cookies provide the foundation of keeping up with who web a user is and where they have been.

The built-in PHP function setcookie() creates or updates a cookie name/value pair in the user’s browser. A cookie contains information sent by a web server to a user’s browser. Whenever a web page is accessed at the server that meets the requirements, cookies associated with that server (that have not expired) are sent back without modification to the server.

The basic cookie consists of a name and a value. For example, a cookie with name “user” can be set to the user’s username, possibly encoded for security. To set the cookie user with the value “qmchenry,” use this command:


This cookie has a default expiration time of 0, which means it will persist until the browser is closed.

It is important to note that cookie information is sent in the web page response headers and, like other times PHP needs to change header values, the setcookie function must be called before any output is sent to the user.


About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

Leave a Reply