How to Use 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 examples for setting cookies with different lifetimes and scopes, while also noting how to read them via $_COOKIE.
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 a cookie's value and attributes. This article explains how to use setcookie .
Below is the basic syntax for using the setcookie function:
setcookie(name, value, expire, path, domain, secure, httponly);Parameter description:
name : the cookie name (required).
value : the cookie value (string or other data type).
expire : expiration time; default 0 (expires when the browser closes) or 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 : whether the cookie should be sent only over HTTPS; default false.
httponly : whether the cookie is accessible only through HTTP (not JavaScript); 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”, expiring in one month and available to the entire domain:
setcookie("username", "John", time()+2592000, "/");3. Set a cookie named “rememberMe” with value “true”, expiring in one week and scoped to a subdomain:
setcookie("rememberMe", "true", time()+604800, "/", "subdomain.example.com");4. Set a cookie named “theme” with value “dark”, expiring in one year, sent only over HTTPS, and marked HttpOnly:
setcookie("theme", "dark", time()+31536000, "/", "", true, true);You can choose different parameters according to your actual requirements to set and customize cookies. After setting a cookie, its value can be read using PHP’s $_COOKIE superglobal.
Summary:
By using PHP’s setcookie function, developers can easily set and manage cookies. Specifying various parameters allows customization of the cookie’s value, expiration, scope, and security attributes to meet project needs. In practice, cookies should be configured responsibly based on security considerations and business requirements to enhance user experience and functionality.
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.