Table of Contents
You return to a website, and the user experience is much better–almost like it’s based around you. This small (sometimes massive) but powerful convenience is made possible by cookies, a core feature of web development.
Cookies in PHP let you store user data directly in the browser. That means personalized experiences, session management, and seamless navigation. And you can use it to implement a “Remember Me” feature, track user activity, or save preferences.
So this blog showcases how to use cookies in PHP, from setting and modifying to updating and deleting them. Let’s look at ways to harness them responsibly and effectively.
What is Cookies in PHP?
Cookies are small pieces of data stored in a user’s browser by a website. They allow web applications to remember information—like login sessions, shopping cart items, or language preferences—between visits.
How Cookies Work
- Server-Side Creation: A website (via PHP or another backend language) generates a cookie and sends it to the browser.
- Client-side Storage: The browser stores the cookie locally.
- Automatic Submission: With each subsequent request, the browser sends the cookie back to the server. That enables persistent user tracking.
Example of a Cookie in PHP
Here’s a breakdown of a real-world cookie, showing each component in action.
setcookie(
"user_session", // Name (identifier)
"a1b2c3d4e5", // Value (stored data)
time() + 86400, // Expiration (1 day from now)
"/account", // Path (only accessible in /account)
".example.com", // Domain (works on all subdomains)
true, // Secure (HTTPS only)
true // HttpOnly (no JavaScript access)
);
What this cookie does:
- Stores a session ID (
a1b2c3d4e5
) under the nameuser_session
. - Expires in 24 hours. After that, the browser deletes it.
- Restricted to
/account
path. It won’t be sent to other site sections. - Works on all subdomains (e.g.,
shop.example.com
,blog.example.com
). - Secure & HttpOnly, so it protects against theft and XSS attacks.
In summary, cookies in PHP are small pieces of data stored in a user’s browser to remember information like sessions, preferences, or cart items. They are created server-side, stored client-side, and sent back to the server with each request for persistent tracking and functionality.
If you need secure, reliable cookie implementation for your web application, then hire dedicated PHP developers to build advanced, privacy-focused features that enhance user experience and protect sensitive data.
How to Set Cookies in PHP?
Cookies in PHP are created using the setcookie()
function. It sends an HTTP header to the browser to store the data. Here’s the basic syntax:
setcookie(name, value, expire, path, domain, secure, httponly);
name
(required): The cookie’s identifier (e.g.,"username"
).value
(required): The data to store (e.g.,"john_doe"
).expire
(optional): When the cookie expires (Unix timestamp).path
(optional): The server path where the cookie is valid (/ for the entire site).domain
(optional): The domain where the cookie works (example.com).secure
(optional): Iftrue
, send only over HTTPS.httponly
(optional): Iftrue
, prevents JavaScript access (security best practice).
Example of a Simple Cookie Setup
<?php
// Set a cookie that expires in 1 hour
setcookie("user", "Alice", time() + 3600, "/");
echo "Cookie 'user' has been set!";
?>
Example of a Secure, HTTP-Only Cookie
<?php
setcookie(
"auth_token",
"abc123xyz",
time() + 86400, // Expires in 1 day
"/", // Available across the whole site
"example.com", // Domain
true, // HTTPS only
true // HTTP-only (no JS access)
);
?>
Make sure to set the cookies before any HTML output (headers are sent first).
How to Use Cookies in PHP?
Cookies enable websites to remember user data between page visits. You can use cookies in PHP through the $_COOKIE
superglobal array. Here’s how to work with them effectively:
Retrieving the Cookies
To access a cookie, use PHP’s $_COOKIE
superglobal array. Here’s an example:
<?php
if (isset($_COOKIE["user"])) {
echo "Welcome back, " . htmlspecialchars($_COOKIE["user"]);
} else {
echo "No user cookie found.";
}
?>
Always check if a cookie exists with isset()
before accessing it. And use htmlspecialchars()
to prevent XSS attacks when displaying cookie data.
Updating the Cookies
To modify a cookie, simply overwrite it using setcookie()
with new values. Here’s an example:
<?php
if (isset($_COOKIE["user"])) {
// Update the cookie to expire in 2 days
setcookie("user", $_COOKIE["user"], time() + 172800, "/");
echo "Cookie updated!";
}
?>
The browser must receive the updated cookie before changes take effect.
Deleting the Cookies
To remove a cookie, set its expiration to a past time. Here’s an example:
<?php
if (isset($_COOKIE["user"])) {
setcookie("user", "", time() - 3600, "/");
echo "Cookie deleted!";
}
?>
So, cookies are managed using the $_COOKIE superglobal to retrieve data, setcookie() to update values, and by setting a past expiration date to delete them. Always validate existence and sanitize output to maintain security.
Best Practices for Using Cookies in PHP
Cookies are vital in conducting the best practices for PHP security. But, it also requires careful handling to ensure security, user privacy, and an optimized browsing experience.
Set Secure & HTTP-Only Flags
Always enable Secure
(HTTPS-only) and HTTP-Only
(blocks JavaScript access) to protect cookies from theft and XSS attacks:
setcookie("session_id", "abc123", time() + 3600, "/", "example.com", true, true);
Limit Cookie Lifetime
Avoid excessively long expiration times. Use short-lived sessions for sensitive data and renew them as needed:
setcookie("preferences", "dark_mode", time() + 86400); // 1 day
Sanitize & Validate Cookie Data
Never trust cookie values—always sanitize input to prevent injection attacks:
$clean_user = htmlspecialchars($_COOKIE['username']);
Avoid Storing Sensitive Data
Cookies are stored client-side and can be tampered with. Store session tokens instead of raw passwords or personal info.
Comply with Privacy Laws (GDPR, CCPA)
Inform users about cookie usage and obtain consent before setting non-essential tracking cookies.
To put it simply, when using cookies in PHP, follow best practices like enabling Secure and HTTP-Only flags, limiting cookie lifetimes, sanitizing data, avoiding sensitive storage, and complying with privacy laws. Using SameSite attributes can also help prevent CSRF attacks.
FAQs About How to Use Cookies in PHP
What’s the difference between cookies and sessions?
Cookies store data in the user’s browser, so the information stays client-side. Sessions store data on the server, and the browser only keeps a small session ID (usually in a cookie) to link to it. Sessions are generally more secure for sensitive data since the actual information never leaves the server.
Are cookies secure for storing login sessions?
Cookies alone aren’t fully secure for storing sensitive information. The safest approach is to store only a session ID in the cookie and keep the actual data on the server. Always use HTTPS and set the HttpOnly and Secure flags to protect cookies from theft and unauthorized access.
How do I make cookies work across subdomains?
To share a cookie between subdomains like shop.example.com and blog.example.com, set its domain parameter to .example.com (with a leading dot). This tells the browser the cookie is valid for all subdomains under the main domain.
Do cookies work if JavaScript is disabled?
Yes. Cookies are part of HTTP headers, so they work even if JavaScript is turned off. However, JavaScript-based storage like localStorage or sessionStorage will stop working if JavaScript is disabled.
Let’s Summarize
Cookies are a fundamental part of web development. You get personalized user experiences, session management, and seamless interactions. It’s important to understand when to set, retrieve, update, and delete cookies in PHP. That’s how you build more dynamic and user-friendly websites.
Remember to prioritize security with HttpOnly and Secure flags. And respect user privacy with proper consent mechanisms. Plus, make sure to always validate cookie data to prevent vulnerabilities.
Ready to level up your PHP project with secure, high-performance features? Then consider opting for PHP development services to ensure success.