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.