Definition and usage
The Setcookie () function sends an HTTP cookie to the client.
A cookie is a variable that is sent to the browser by the server. A cookie is usually a small text file that the server embeds into a user's computer. This cookie is sent whenever the computer requests a page through a browser.
The name of the cookie is specified as a variable of the same name. For example, if the cookie being sent is named "name", a variable named $user is automatically created, containing the value of the cookie.
There can be no loss before a cookie is assigned a value. If successful, the function returns True, otherwise false is returned.
Note: Cookie settings must be refreshed later to take effect.
Grammar
Setcookie (Name,value,expire,path,domain,secure)
Parameter description
Name is required. Specifies the name of the cookie.
Value is required. Specifies the value of the cookie.
Expire is optional. Specify the validity period of the cookie.
Path is optional. Specifies the server path of the cookie.
Domain is optional. Specifies the domain name of the cookie.
Secure is optional. Specifies whether to transfer cookies through a secure HTTPS connection.
Hints and Notes
Note: You can access the value of a COOKIE named "User" by $HTTP _cookie_vars["user"] or $_cookie["user".
Note: When a cookie is sent, the value of the cookie is automatically URL-encoded. The URL is decoded when it is received. If you don't need this, you can use Setrawcookie () instead.
Example 1
Set up and send cookies:
<?php
$value = "My cookie value";
Send a simple cookie
Setcookie ("TestCookie", $value);
? >
<?php
$value = "My cookie value";
Send a cookie that expires in the 24 child
Setcookie ("TestCookie", $value, Time () +3600*24);
? >
Example 2
Different ways to retrieve cookie values:
Output individual Cookies
echo $_cookie["TestCookie"];
echo "<br/>";
echo $HTTP _cookie_vars["TestCookie"];
echo "<br/>";
Export All Cookies
Print_r ($_cookie);
?></body>
Output:
My cookie value
My cookie value
Array ([TestCookie] = My cookie value)
Example 3
Delete a cookie by setting the expiration date to the last Date/time:
<?php
Set the expiration date to one hour ago
Setcookie ("TestCookie", "", Time ()-3600);
? >
Example 4
Create an array cookie:
<?php
Setcookie ("Cookie[three]", "Cookiethree");
Setcookie ("Cookie[two]", "cookietwo");
Setcookie ("Cookie[one]", "Cookieone");
Output cookie (after reloading the page)
if (Isset ($_cookie["COOKIE")) {
foreach ($_cookie["COOKIE"] as $name = = $value) {
echo "$name: $value <br/>";
}
}
? >
Output:
Three:cookiethree
Two:cookietwo
One:cookieone
Example 5
An issue that does not take effect when a cookie is set. Usually the reason why the scope is not set
<?php
Setcookie ("A", "BB", Time () +3600, "/", ". hi-docs.com");
Note that the domain name is set to its own
?>
PHP Settings Setcookie