PHP setrawcookie()
Function
Definition and Usage
The setrawcookie()
function sends an HTTP cookie without URL encoding the cookie value.
Cookies are variables sent by the server to the browser. Cookies are typically small text files embedded by the server into the user's computer. Whenever the same computer requests a page through a browser, this cookie is sent as well.
The name of the cookie is automatically assigned to a variable of the same name. For example, if a cookie named "user" is sent, a variable named $user is automatically created, containing the value of the cookie.
Cookies must be assigned before sending any other output to the client.
The function returns TRUE if successful, and FALSE if it fails.
Syntax
Parameter | 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. time()+3600*24*30 sets the cookie to expire in 30 days. If this parameter is not set, the cookie will automatically expire when the session ends (i.e., when the browser is closed). |
path | Optional. Specifies the server path of the cookie. If the path is set to "/", the cookie will be valid within the entire domain. If the path is set to "/test/", the cookie will be valid within the test directory and all its subdirectories. The default path value is the current directory where the cookie is set. |
domain | Optional. Specifies the domain of the cookie. To make the cookie valid for all subdomains of example.com, set the domain to ".example.com". When the domain is set to www.example.com, the cookie is only valid for the www subdomain. |
secure | Optional. Specifies whether the cookie should be transmitted over a secure HTTPS connection. Set to TRUE if the cookie requires a secure HTTPS connection, otherwise FALSE. The default is FALSE. |
Tips and Notes
Tip: You can access the value of a cookie named "user" using $HTTP_COOKIE_VARS["user"] or $_COOKIE["user"].
Note: The setrawcookie()
function is almost identical to the setcookie()
function, except that it does not automatically URL-encode the cookie value when sending it to the client.
Example 1
Setting and sending a cookie:
Example 2
Different methods to retrieve the cookie value (after the cookie is set):
The above code will output:
Example 3
Deleting a cookie by setting the expiration date to a past date/time:
Example 4
Creating an array cookie:
The above code will output: