Wednesday, June 12, 2024
HomeWeb application programmingPHP programmingPHP: Set or Create a Simple Browser Cookie with setcookie

PHP: Set or Create a Simple Browser Cookie with setcookie

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:

setcookie('user','qmchenry');

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.

Quinn McHenry
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.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

LATEST REVIEWS

Recent Comments

error: Content is protected !!