How to Use PHP's setcookie Function to Set Cookies
This article explains PHP's setcookie function, detailing its syntax, parameter meanings, and providing several practical code examples for creating cookies with different lifetimes, paths, domains, and security flags, while also noting how to retrieve cookies using the $_COOKIE superglobal.
In website development, cookies are a common technique used to store a small amount of data in the user's browser so that information can be passed between pages. PHP provides a function called setcookie to set the value and attributes of a cookie.
The basic syntax of setcookie is:
setcookie(name, value, expire, path, domain, secure, httponly);Parameter description:
name : the cookie name (required).
value : the cookie value; can be a string or other data type.
expire : expiration time; default is 0 (expires when the browser closes). It can also be a UNIX timestamp specifying an exact expiry.
path : the path on the server in which the cookie will be available; default is the current page.
domain : the domain that the cookie is available to; default is empty, meaning the current domain.
secure : whether the cookie should be sent only over HTTPS; default is false .
httponly : whether the cookie is accessible only through the HTTP protocol; default is false (it can be accessed via JavaScript).
Below are some common usage examples:
1. Set a cookie named "username" with the value "John" that expires in one hour:
setcookie("username", "John", time()+3600);2. Set a cookie named "username" with the 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 the value "true" that expires in one week and is scoped to a sub‑domain:
setcookie("rememberMe", "true", time()+604800, "/", "subdomain.example.com");4. Set a cookie named "theme" with the value "dark" that expires in one year, is sent only over HTTPS, and is inaccessible to JavaScript:
setcookie("theme", "dark", time()+31536000, "/", "", true, true);After setting cookies, you can read them using PHP's $_COOKIE superglobal variable.
Conclusion: By using PHP's setcookie function, you can easily create and manage cookies. By specifying different parameters you can customize the cookie's value, expiration time, scope, and security attributes to meet the needs of your project. In practice, consider security and business requirements when configuring cookies to provide a better user experience and functional interaction.
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.