-
Hajipur, Bihar, 844101
Cookies are one of the most common ways to store information about users between different visits to a website. When a user browses a site, PHP can send small data files called cookies to the user’s browser. The browser then saves them and sends them back to the server every time the same site is visited again. This allows websites to “remember” things like usernames, preferences, themes, or login sessions, even after the user closes their browser or restarts their computer.
A cookie is essentially a piece of text data saved in the user’s browser. Each cookie has a name and a value, and it can also include an expiration date, a path, and other optional parameters. PHP interacts with cookies through two main tools:
The setcookie()
function — used to create or modify a cookie.
The $_COOKIE
superglobal — used to read cookies that have already been stored.
Cookies make web applications more personalized. For instance, an online store can use cookies to keep track of what items a visitor adds to their cart. A learning website might use cookies to remember which course a user last viewed. This makes browsing smoother and more consistent.
The PHP setcookie()
function is simple but powerful. It allows you to define how a cookie behaves.
setcookie(name, value, expire, path, domain, secure, httponly);
Each parameter serves a purpose:
name: The unique name for the cookie.
value: The data you want to store (string only).
expire: The time when the cookie will expire, in Unix timestamp format.
path: Defines where on the website the cookie is available (usually “/” for the whole site).
domain: Specifies which domain the cookie belongs to.
secure: If set to true
, the cookie is only sent over HTTPS.
httponly: If true
, the cookie can’t be accessed through JavaScript, improving security.
All parameters after the first two are optional. If you don’t set an expiration time, the cookie will last only until the browser is closed.
Cookies must be set before any output (like HTML) is sent to the browser. PHP sends cookies in the HTTP headers, so if you try to set a cookie after HTML has started rendering, you’ll get an error.
Example:
<?php
setcookie("user", "Vrinda", time() + 3600, "/"); // expires in 1 hour
?>
<html>
<body>
<?php
if (isset($_COOKIE["user"])) {
echo "Welcome back, " . $_COOKIE["user"];
} else {
echo "Welcome, guest!";
}
?>
</body>
</html>
In this example:
The cookie is named user and stores the value Vrinda.
It will expire in one hour from the time it’s created.
The path /
means it’s accessible across the entire site.
When the user visits the page again, PHP checks whether the cookie exists and greets them accordingly.
Reading a cookie in PHP is straightforward using the $_COOKIE
array. Each cookie can be accessed by its name. You can print or use the value however you want in your application.
<?php
if (isset($_COOKIE["user"])) {
echo "Hello, " . $_COOKIE["user"];
} else {
echo "No cookie found!";
}
?>
If the cookie exists, the script displays its value. If it doesn’t, the message “No cookie found!” is shown. It’s always a good practice to check if a cookie is set before trying to use it.
Cookies can be updated by calling setcookie()
again with the same name but a new value. The new cookie will replace the old one.
<?php
setcookie("user", "Anjali", time() + 3600, "/"); // updates cookie value
echo "Cookie updated successfully.";
?>
Here, the cookie named user now stores the value “Anjali” instead of “Vrinda.” The expiration time also refreshes for one more hour.
To delete a cookie, you simply set its expiration time in the past. This signals the browser to remove it.
<?php
setcookie("user", "", time() - 3600, "/");
echo "Cookie deleted.";
?>
Once deleted, the cookie will no longer exist in $_COOKIE
. Note that deleting only affects future page loads — it doesn’t instantly remove it from the current page’s $_COOKIE
array.
A website often needs to remember multiple pieces of information — for example, a username, a selected theme, and preferred language. You can create multiple cookies easily by calling setcookie()
for each one.
<?php
setcookie("username", "Ritika", time() + 3600, "/");
setcookie("language", "English", time() + 3600, "/");
setcookie("theme", "light", time() + 3600, "/");
?>
Each cookie can be retrieved separately using $_COOKIE["username"]
, $_COOKIE["language"]
, or $_COOKIE["theme"]
.
Cookies can last for as long as you want — hours, days, or even years. The expiration time is calculated using the current time plus the number of seconds the cookie should remain valid.
For example, to create a cookie that lasts for one week:
<?php
$oneWeek = time() + (7 * 24 * 60 * 60);
setcookie("theme", "dark", $oneWeek, "/");
echo "Cookie set for 7 days.";
?>
If you want a cookie that never expires, set a long duration — but be careful with this, as permanent cookies can raise privacy concerns.
Security is crucial when working with cookies. Cookies can be stolen through JavaScript-based attacks if not properly protected. PHP allows two important options:
Secure: Ensures the cookie is sent only over HTTPS.
HttpOnly: Prevents client-side scripts from reading the cookie.
Here’s how you can create a secure cookie:
<?php
setcookie("session_token", "abc123xyz", time() + 3600, "/", "", true, true);
?>
This cookie:
Works only on HTTPS connections.
Cannot be accessed via JavaScript.
Such settings are especially important for session or authentication cookies.
A common real-world use of cookies is to remember a user’s name between visits. Consider the example below:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
setcookie("username", $username, time() + (86400 * 30), "/"); // stores for 30 days
echo "Hello, " . $username . ". We'll remember you next time!";
}
?>
<form method="post">
Enter your name: <input type="text" name="username" required>
<input type="submit" value="Save">
</form>
<?php
if (isset($_COOKIE["username"])) {
echo "<br>Welcome back, " . $_COOKIE["username"] . "!";
}
?>
Here, the user enters their name once. The browser stores it as a cookie, and when the user visits the site again, the script greets them automatically.
Always call setcookie()
before any HTML output.
Cookies are stored on the client side, so they can be viewed and deleted by the user.
Never store passwords or sensitive information in cookies.
Use encryption if you must store confidential data.
Always validate and sanitize cookie values before using them.
Cookies make websites feel personal and convenient. They help create a seamless experience where users don’t have to re-enter their preferences or data repeatedly. However, they should be used responsibly. A good developer knows how to balance usability with privacy and security. By understanding how cookies work in PHP, you can build user-friendly, efficient, and secure web applications.
Create a cookie named username
with the value "Ritika"
that expires after 2 hours.
Write PHP code to check if a cookie named theme
exists, and if it does, display its value.
How would you update the value of a cookie named user_email
to "vrinda@example.com"
?
Write a script to delete a cookie named session_id
.
Set three cookies — name
, email
, and city
— each valid for 24 hours.
Create a cookie named language
that lasts for 7 days and is available only on the /dashboard
path.
Write a secure cookie named auth_token
that is both HttpOnly
and works only over HTTPS.
Create a cookie form where the user enters their favorite color, store it in a cookie, and display it on reload.
How would you check if a cookie named visit_count
exists? If not, create it with a starting value of 1, and if it exists, increment it by 1.
Write PHP code to display all cookies stored in the user’s browser using a loop.