Master PHP’s setcookie: Create Secure, Custom Cookies in Minutes

This guide explains how to use PHP's setcookie function to create and manage browser cookies, covering syntax, each parameter's purpose, practical code examples, and security considerations for effective backend development.

php Courses
php Courses
php Courses
Master PHP’s setcookie: Create Secure, Custom Cookies in Minutes

Cookies store small pieces of data in a user's browser to share information across pages, and PHP provides the setcookie function for creating and configuring them.

Syntax

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

Parameter Details

name : The cookie's name (required).

value : The cookie's value; can be a string or other data type.

expire : Expiration time. Default 0 means the cookie expires when the browser closes; otherwise provide a UNIX timestamp.

path : The path scope of the cookie. Default is the current page.

domain : The domain scope. Default empty means the current domain.

secure : If true, the cookie is sent only over HTTPS. Default false.

httponly : If true, the cookie is inaccessible to JavaScript (HTTP‑only). Default false.

Common Usage Examples

Set a cookie named "username" with value "John" that expires in one hour: setcookie("username", "John", time()+3600); Set a cookie "username" for one month, available site‑wide:

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

Set a cookie "rememberMe" with value "true" for one week, limited to a subdomain:

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

Set a cookie "theme" with value "dark" for one year, HTTPS‑only and HTTP‑only:

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

After setting cookies, they can be read using PHP's $_COOKIE superglobal.

Conclusion

By using setcookie, developers can easily create and manage cookies, customizing name, value, expiration, scope, and security flags to meet project needs, improve user experience, and adhere to security best practices.

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.

SecurityWeb Developmentcookiessetcookie
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.