Setting a Cookie with PHP

You can set a cookie in a PHP script in two ways. You can use the header() function to set the Set-Cookie header. The header() function requires a string that will then be included in the header section of the server response. Because headers are sent automatically for you, header() must be called before any output at all is sent to the browser:

header ("Set-Cookie: vegetable=artichoke; expires=Wed, 27-Aug-03 14:39:58 GMT;
path=/; domain=yourdomain.com");

Although not difficult, this method of setting a cookie would require you to build a function to construct the header string. Formatting the date as in this example and URL-encoding the name/value pair would not be a particularly arduous task. It would, however, be ...

Get Sams Teach Yourself PHP, MySQL® and Apache All in One 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.