PHP: Set or create a simple browser cookie with setcookie

Home -> Programming -> Web -> PHP

7294 views

From the computer of: qmchenry (339 recipes)
Created: Jul 14, 2006


Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

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 a web user is, where they've been, and what they had for lunch. Well, who and where, anyway.

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 that server that meets the requirements, cookies associated with that server (that haven't 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.

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  PHP: Delete or expire a browser cookie
  PHP: Read a browser cookie value
  PHP: Create a File on your Server
  Redirect to another web page using PHP
  Make Wordpress Stop Replacing Double Dash with Em-dash
  PHP: Delete or unlink a file on the server
  PHP syntax: for loop basics
  PHP: Password Protect Your pages.
  PHP: Upload Files to the server
  PHP syntax: create an associative array

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.