Using PHP's setcookie Function to Create and Manage Cookies

This article explains the PHP setcookie function, detailing its syntax, parameters, and practical examples for setting cookies with various attributes such as expiration time, path, domain, security, and HttpOnly flags.

php Courses
php Courses
php Courses
Using PHP's setcookie Function to Create and Manage Cookies

In web development, cookies are small pieces of data stored in a user's browser to transfer information between pages, and PHP provides the setcookie function to create and configure them.

The basic syntax is:

setcookie(name, value, expire, path, domain, secure, httponly);

Parameter descriptions:

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 provide a Unix timestamp.

path : the path on the server where the cookie is available; default is the current page.

domain : the domain that can access the cookie; default is the current domain.

secure : if true, the cookie is sent only over HTTPS; default is false.

httponly : if true, the cookie is inaccessible to JavaScript (only sent via HTTP); default is false.

Common usage examples: setcookie("username", "John", time()+3600); Sets a cookie named username with value John that expires in one hour.

setcookie("username", "John", time()+2592000, "/");

Sets the same cookie to expire in one month and be available across the entire domain.

setcookie("rememberMe", "true", time()+604800, "/", "subdomain.example.com");

Creates a cookie that lasts a week and is limited to a specific subdomain.

setcookie("theme", "dark", time()+31536000, "/", "", true, true);

Sets a cookie that lasts a year, is sent only over HTTPS, and is HttpOnly.

After setting cookies, the $_COOKIE superglobal can be used to read their values. Properly configuring cookie attributes enhances security and user experience.

In summary, the PHP setcookie function allows developers to easily set and manage cookies by specifying appropriate parameters to meet project requirements and security considerations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendCookiesetcookie
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.