Introduction
Cookies in PHP are used to store small amounts of information in a visitor’s browser. They help websites remember user preferences, login information, and other details between page visits. In this chapter, you will practise creating, accessing, updating, and deleting cookies through practical examples using PHP.
Question 1: Create a Cookie Using setcookie()
Problem Statement
Create a PHP program that stores a student’s name in a cookie for one hour.
PHP Solution
<?php
setcookie("student_name", "Rahul", time() + 3600, "/");
echo "Student cookie has been created.";
?>
Sample Output
Student cookie has been created.
Explanation
setcookie()creates a cookie in the visitor’s browser.student_nameis the cookie name.Rahulis the cookie value.time() + 3600sets the expiry time to one hour from now./makes the cookie available throughout the website.
Important: Cookies must be set before any HTML output or whitespace is sent to the browser.
Concepts Covered
setcookie()- Cookie creation
- Cookie expiry time
Question 2: Read a Cookie Using $_COOKIE
Problem Statement
Create a PHP program that displays a student’s name stored in a cookie.
PHP Solution
<?php
setcookie("student_name", "Rahul", time() + 3600, "/");
if (isset($_COOKIE["student_name"])) {
echo "Student Name: " . $_COOKIE["student_name"];
} else {
echo "Cookie is not available.";
}
?>
Sample Output
On the first request:
Cookie is not available.
On a subsequent request, after the browser has stored the cookie:
Student Name: Rahul
Explanation
$_COOKIEis a PHP superglobal array used to access cookies sent by the browser.isset()checks whether the cookie exists in the current request.- A cookie created with
setcookie()normally becomes available through$_COOKIEon the next request, not immediately in the same request.
Concepts Covered
$_COOKIEisset()- Reading cookies
- Browser requests
Question 3: Set a Cookie with a Custom Expiry Time
Problem Statement
Create a PHP program that stores a user’s preferred language in a cookie for seven days.
PHP Solution
<?php
$language = "English";
$expiry = time() + (7 * 24 * 60 * 60);
setcookie("preferred_language", $language, $expiry, "/");
echo "Language preference has been saved.";
?>
Sample Output
Language preference has been saved.
Explanation
$languagestores the preferred language.time()returns the current Unix timestamp.7 * 24 * 60 * 60calculates seven days in seconds.setcookie()stores the language with the calculated expiry time.
Concepts Covered
- Cookie expiry
- Unix timestamps
- Cookie preferences
Question 4: Update an Existing Cookie
Problem Statement
Create a PHP program that updates a user’s existing cookie with a new city name.
PHP Solution
<?php
setcookie("user_city", "Delhi", time() + 86400, "/");
echo "User city cookie has been updated.";
?>
Sample Output
User city cookie has been updated.
Explanation
setcookie()creates or updates a cookie with the specified name.- If
user_cityalready exists, the browser receives the updated value. - The new value becomes available in
$_COOKIEon the next request.
Concepts Covered
- Updating cookies
- Cookie names
- Cookie values
Question 5: Delete a Cookie Using setcookie()
Problem Statement
Create a PHP program that deletes a cookie named student_name.
PHP Solution
<?php
setcookie("student_name", "", time() - 3600, "/");
echo "Student cookie has been deleted.";
?>
Sample Output
Student cookie has been deleted.
Explanation
- Cookies can be deleted by setting their expiry time to a past timestamp.
- The cookie name and path must match the original cookie.
- The browser removes the cookie when it processes the response.
- The deletion is reflected in the next request.
Concepts Covered
- Cookie deletion
- Expiry timestamps
- Cookie path
Question 6: Store Multiple Cookies in PHP
Problem Statement
Create a PHP program that stores a user’s name, city, and preferred course in three separate cookies.
PHP Solution
<?php
setcookie("user_name", "Amit", time() + 86400, "/");
setcookie("user_city", "Delhi", time() + 86400, "/");
setcookie("user_course", "PHP", time() + 86400, "/");
echo "User information cookies have been created.";
?>
Sample Output
User information cookies have been created.
Explanation
- Each cookie has a unique name.
setcookie()creates each cookie separately.- All three cookies are configured to expire after one day.
- Their values can be accessed through
$_COOKIEin a subsequent request.
Concepts Covered
- Multiple cookies
- Cookie storage
- Cookie expiry
Question 7: Check Whether a Cookie Exists
Problem Statement
Create a PHP program that checks whether a user’s login preference cookie exists.
PHP Solution
<?php
if (isset($_COOKIE["remember_me"])) {
echo "Remember Me preference is available.";
} else {
echo "Remember Me preference is not available.";
}
?>
Sample Output
If the cookie exists:
Remember Me preference is available.
If the cookie does not exist:
Remember Me preference is not available.
Explanation
isset()checks whether a cookie is available in the current request.$_COOKIE["remember_me"]accesses the cookie value.- If the cookie is missing, the
elseblock executes.
Concepts Covered
isset()- Cookie existence
- Conditional statements
Question 8: Store a Website Theme Preference in a Cookie
Problem Statement
Create a PHP program that stores a user’s preferred website theme, such as Dark or Light, in a cookie.
PHP Solution
<?php
$theme = "Dark";
setcookie("website_theme", $theme, time() + (30 * 86400), "/");
echo "Selected Theme: " . $theme;
echo "\nTheme preference saved.";
?>
Sample Output
Selected Theme: Dark
Theme preference saved.
Explanation
$themestores the selected website theme.setcookie()saves the theme in the browser.30 * 86400sets the cookie expiry to 30 days.- The website can read this cookie on later requests to apply the user’s preferred theme.
Concepts Covered
- Website preferences
- Cookie storage
- Long-term cookies
Question 9: Set a Secure Cookie Using Cookie Options
Problem Statement
Create a PHP program that stores a user’s session preference using cookie options for security.
PHP Solution
<?php
setcookie("user_preference", "dark_mode", [
"expires" => time() + 3600,
"path" => "/",
"secure" => true,
"httponly" => true,
"samesite" => "Lax"
]);
echo "Secure cookie settings applied.";
?>
Sample Output
Secure cookie settings applied.
Explanation
expiressets the cookie’s expiry time.pathcontrols which website paths can access the cookie.securesends the cookie only over HTTPS connections.httponlyprevents JavaScript from accessing the cookie throughdocument.cookie.samesitehelps control when browsers send cookies with cross-site requests.
Important: The secure option should be used on an HTTPS website. On a normal HTTP local development server, the browser may not send this cookie.
Concepts Covered
- Secure cookies
- Cookie options
httponlysamesite- HTTPS
Question 10: Build a Simple User Preference System Using Cookies
Problem Statement
Create a PHP program that saves a user’s name and preferred language in cookies and displays the saved information on a subsequent page request.
PHP Solution
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$name = $_POST["name"];
$language = $_POST["language"];
setcookie("user_name", $name, time() + 86400, "/");
setcookie("user_language", $language, time() + 86400, "/");
echo "User preferences saved successfully.";
} else {
if (
isset($_COOKIE["user_name"]) &&
isset($_COOKIE["user_language"])
) {
echo "Welcome, " . htmlspecialchars($_COOKIE["user_name"]);
echo "\nPreferred Language: " .
htmlspecialchars($_COOKIE["user_language"]);
} else {
echo "No saved preferences found.";
}
}
?>
<form method="POST">
<label>Enter Name:</label>
<input type="text" name="name" required>
<br><br>
<label>Select Language:</label>
<select name="language">
<option value="English">English</option>
<option value="Hindi">Hindi</option>
<option value="French">French</option>
</select>
<br><br>
<button type="submit">Save Preferences</button>
</form>
Sample Output
After submitting the form:
User preferences saved successfully.
On a subsequent request:
Welcome, Rahul
Preferred Language: English
Explanation
- The form collects the user’s name and preferred language.
$_SERVER["REQUEST_METHOD"]checks whether the form was submitted using POST.$_POSTreceives the submitted form values.setcookie()saves both preferences in the browser.- On a subsequent request,
$_COOKIEretrieves the saved values. htmlspecialchars()helps prevent HTML injection when displaying user-supplied text.
Concepts Covered
- Cookies with HTML forms
$_POST$_COOKIE$_SERVERhtmlspecialchars()- User preference management
Key Takeaways
- Cookies store small amounts of information in a visitor’s browser.
setcookie()creates or updates a cookie.$_COOKIEreads cookie values.isset()checks whether a cookie exists in the current request.- Cookie expiry is controlled using timestamps.
- Setting an expiry time in the past deletes a cookie.
- Cookies are generally available through
$_COOKIEon a subsequent request. - Cookie options such as
secure,httponly, andsamesiteimprove security. - Cookies must be set before sending output to the browser.
- Cookies should not be used to store passwords or sensitive information.
Frequently Asked Questions (FAQs)
1. What are cookies in PHP?
Cookies are small pieces of data stored in a visitor’s browser. PHP can create, read, update, and delete cookies.
2. Which function is used to create cookies in PHP?
The setcookie() function is used to create or update cookies in PHP.
3. How can we access cookies in PHP?
You can access cookies using the $_COOKIE superglobal array.
4. How can we delete a cookie in PHP?
You can delete a cookie by calling setcookie() with the same name and path and setting its expiry time to a past timestamp.
5. What is the default lifetime of a cookie?
If no expiry time is provided, a cookie is normally a session cookie. It is generally removed when the browser session ends, depending on browser behavior.
6. Can we store multiple cookies in PHP?
Yes. You can create multiple cookies by calling setcookie() with different cookie names.
7. Why must setcookie() be called before HTML output?
setcookie() sends an HTTP header to the browser. Headers must be sent before the response body starts.
8. What is the difference between cookies and sessions?
Cookies are stored in the browser, while PHP session data is generally stored on the server. A session identifier is commonly stored in a browser cookie.
9. What is the httponly option in PHP cookies?
The httponly option prevents JavaScript from accessing a cookie through browser APIs such as document.cookie.
10. Are cookies safe for storing passwords?
No. Passwords and sensitive information should not be stored directly in cookies. Authentication systems should use secure, appropriately configured session or token mechanisms.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
