How to Use PHP's setcookie Function to Set Cookies
This article explains how to use PHP's setcookie function to create and customize browser cookies, covering its syntax, parameter meanings, and practical examples such as setting expiration, path, domain, secure and HttpOnly flags.
In website development, cookies are a common technique for storing small amounts of data in the user's browser to transfer information between pages. PHP provides the setcookie function to set cookie values and attributes.
The basic syntax 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; 0 means the cookie expires when the browser closes, otherwise a UNIX timestamp.
path : The path on the server where the cookie will be available. Default is the current page.
domain : The domain that the cookie is available to. Default is the current domain.
secure : If true, the cookie is sent only over HTTPS connections. Default false.
httponly : If true, the cookie is accessible only through HTTP protocol, not via JavaScript. Default false.
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 available across 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 HttpOnly:
setcookie("theme", "dark", time()+31536000, "/", "", true, true);After setting cookies, you can read them using PHP's $_COOKIE superglobal.
Conclusion
By using PHP's setcookie function, developers can easily set and manage cookies, customizing attributes such as value, expiration, scope, security, and HttpOnly flags to meet project requirements and improve user experience.
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.