Using PHP setcookie Function to Set Cookies
This article explains the PHP setcookie function, detailing its syntax, parameters such as name, value, expiration, path, domain, secure, and httponly, and provides multiple practical code examples for setting cookies with various scopes, lifetimes, and security options.
In web development, cookies are a common technique for storing small amounts of data in a user's browser to transfer information between pages. PHP provides the setcookie function to set cookie values and attributes.
The basic syntax of the setcookie function is:
setcookie(name, value, expire, path, domain, secure, httponly);Parameter description:
name : the cookie name (required).
value : the cookie value, which can be a string or other data type.
expire : the expiration time; default 0 (expires when the browser closes) or a UNIX timestamp for a specific time.
path : the cookie path; default is the current page.
domain : the cookie domain; default is empty (current domain).
secure : whether to send the cookie only over HTTPS; default false.
httponly : whether the cookie is accessible only via HTTP protocol; default false.
Below are some common usage examples:
1. Set a cookie named "username" with value "John" that expires in one hour:
setcookie("username", "John", time()+3600);2. Set a cookie named "username" with value "John" that expires in one month and is valid for the entire domain:
setcookie("username", "John", time()+2592000, "/");3. Set a cookie named "rememberMe" with value "true" that expires in one week and is scoped to a subdomain:
setcookie("rememberMe", "true", time()+604800, "/", "subdomain.example.com");4. Set a cookie named "theme" with value "dark" that expires in one year, is sent only over HTTPS, and is HTTP‑only:
setcookie("theme", "dark", time()+31536000, "/", "", true, true);Depending on the requirements, different parameters can be used to customize cookies. After setting a cookie, the PHP superglobal $_COOKIE can be used to read its value.
Summary:
By using PHP's setcookie function, developers can easily set and manage cookies. Specifying different parameters allows customization of the cookie's value, expiration, scope, and security attributes to meet project needs, while considering security and user experience.
PHP实战开发极速入门
扫描二维码免费领取学习资料
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.