(PHP 4, PHP 5, PHP 7)
setcookie — Send a cookie
bool setcookie ( string
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including <html> and <head> tags as well as any whitespace.
» RFC 6265 provides the normative reference on how each setcookie() parameter is interpreted.
If output exists prior to calling this function,
setcookie() will fail and return
Some examples follow how to send cookies:
Example #1 setcookie() send example
Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5. To see the contents of our test cookie in a script, simply use one of the following examples:
Example #2 setcookie() delete example
When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser. Examples follow how to delete cookies sent in previous example:
Example #3 setcookie() and arrays
You may also set array cookies by using array notation in the cookie name. This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name:
The above example will output:
three : cookiethree two : cookietwo one : cookieone
Multiple calls to setcookie() are performed in the order called.