PHP setrawcookie() function
Definition and Usage
The setrawcookie() function does not URL-encode the cookie value and sends an HTTP cookie.
Cookies are variables sent from the server to the browser. Cookies are typically small text files embedded by the server into the user's computer. Whenever a computer requests a page through the browser, this cookie is sent.
The name of the cookie is specified as the same-named variable. For example, if a cookie named "name" is sent, an automatic variable $user is created containing the value of the cookie.
Cookies must be assigned a value before any other output is sent.
If successful, the function returns true; otherwise, it returns false.
Syntax
setcookie(name,value,expire,path,domain,secure)
Parameters | Description |
---|---|
name | Required. Specifies the name of the cookie. |
value | Required. Specifies the value of the cookie. |
expire | Optional. Specifies the expiration time of the cookie. |
path | Optional. Specifies the server path for the cookie. |
domain | Optional. Specifies the domain of the cookie. |
secure | Optional. Specifies whether the cookie is transmitted over a secure HTTPS connection. |
Tips and Notes
Note:The value of a cookie named "user" can be accessed via $HTTP_COOKIE_VARS["user"] or $_COOKIE["user"].
Note:setrawcookie() versus setcookie() Almost identical, the difference is that the cookie value is not automatically URL-encoded when sent to the client.
Instance
Example 1
Set and send cookies:
<?php $value = "my cookie value"; // Send a simple cookie setrawcookie("TestCookie",$value); ?> <html> <body> ... ...
<?php $value = "my cookie value"; // Send a cookie that expires in 24 hours setrawcookie("TestCookie",$value, time()+3600*24); ?> <html> <body> ... ...
Example 2
Different methods to retrieve cookie values:
<html> <body> <?php // Output individual cookies echo $_COOKIE["TestCookie"]; echo "<br />"; echo $HTTP_COOKIE_VARS["TestCookie"]; echo "<br />"; // Output all cookies print_r($_COOKIE); ?> </body> </html>
Output:
my cookie value my cookie value Array ([TestCookie] => my cookie value)
Example 3
// Delete a cookie by setting the expiration date to a past date/time
<?php // Set expiration date to one hour ago setrawcookie("TestCookie", "", time() - 3600); ?> <html> <body> ... ...
Example 4
Create an array cookie:
<?php setrawcookie("cookie[three]","cookiethree"); setrawcookie("cookie[two]","cookietwo"); setrawcookie("cookie[one]","cookieone"); // Output cookie (after page reload) if (isset($_COOKIE["cookie"])) { foreach ($_COOKIE["cookie"] as $name => $value) { echo "$name : $value <br />"; } } ?> <html> <body> ... ...
Output:
three : cookiethree two : cookietwo one : cookieone