Home>Article>Backend Development> Example of PHP method to set setcookie
The setcookie() function sends an HTTP cookie to the client.
Cookie is a variable sent by the server to the browser. Cookies are typically small text files that a server embeds on a user's computer. This cookie is sent each time the computer requests a page through the 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 cookie's value.
There cannot be any input before assigning a value to the cookie. The function returns true if successful, false otherwise.
Note: The cookie setting must be refreshed before it can take effect.
Syntax
setcookie(name,value,expire,path,domain,secure)
Parameter Description
name Required. Specifies the name of the cookie.
value Required. Specifies the cookie value.
expire Optional. Specifies the validity period of the cookie.
path Optional. Specifies the server path for cookies.
domain Optional. Specifies the domain name for the cookie.
secure Optional. Specifies whether cookies are transmitted over a secure HTTPS connection.
Tips and Notes
Note: The cookie named "user" can be accessed through $HTTP_COOKIE_VARS["user"] or $_COOKIE["user"] value.
Note: When sending a cookie, the cookie value is automatically URL encoded. URL decoding occurs on reception. If you don't need this, you can use setrawcookie() instead.
Example 1
Set and send a cookie:
......
......
Example 2
Different ways to retrieve cookie values:
"; echo $HTTP_COOKIE_VARS["TestCookie"]; echo "
"; // 输出所有 cookie print_r($_COOKIE); ?>
Output:
my cookie value my cookie value Array ([TestCookie] => my cookie value)
Example 3
Delete a cookie by setting the expiration date to a date/time in the past:
......
Example 4
Create An array cookie:
$value){ echo "$name : $value
"; } } ?>......
Output:
three : cookiethree two : cookietwo one : cookieone
Example 5
About the problem that the cookie does not take effect after being set. Usually the reason is that the scope is not set
Recommendation:PHP video tutorial
The above is the detailed content of Example of PHP method to set setcookie. For more information, please follow other related articles on the PHP Chinese website!