1. What is a Cookie? Its Basic Role in a Website
A **Cookie** is a small piece of text data stored on the user’s web browser (such as Chrome or Safari) to temporarily save information about website visitors.
This data includes information such as the date and time the user last visited the site, login status, items placed in the shopping cart, and site display preferences.
The most basic role of a Cookie is user identification. By reading the information stored in this Cookie, a website can recognize, “This person has visited this site before,” or “This person is currently logged in.” This enables convenient features such as the following:
- Maintaining Login Status: Once logged in, you can avoid the hassle of logging in again when you revisit the site, even after closing the browser.
- Shopping Cart: Items placed in the cart remain saved even if you move to other pages or leave the site and return later.
- Site Display Settings: User-specific settings, such as language settings or themes (like dark mode), can be remembered.
Cookies are an essential technology for comfortable site usage and are a critical element to understand as a foundation of web development.
2. Cookie Mechanism in PHP: Data Exchange Between Client and Server
When performing web development using PHP, Cookies are exchanged between the Web server and the **Client (the user’s web browser)**. Understanding this mechanism is the first step in handling Cookies with PHP.
- Client: The user’s web browser (on a PC or smartphone) viewing the website.
- Server: The location where the website data and PHP programs are running (the Web server).
The Flow of Cookie Data
【From Server to Client】Cookie Generation and Transmission (Setting)
- The user accesses the website, and the PHP program executes.
- PHP generates a special header (the Set-Cookie HTTP response header) containing the information to be stored in the user’s browser (e.g., user_id=123).
- The server sends this header back to the browser.
- The browser receives it and saves the specified information (the Cookie) locally.
【From Client to Server】Cookie Retention and Re-transmission (Usage)
- The user then accesses another page on the same site or reloads the current page.
- The browser automatically includes the saved Cookie for that site in the request (the Cookie HTTP request header) and sends it to the server.
- The PHP on the server side receives the sent Cookie data and uses it to identify the user or perform necessary processing.
In this way, Cookies serve to give “state” to the stateless HTTP communication: the server sets them, the browser holds them, and the browser sends them back to the server with every subsequent access.
3. Setting Cookies: Basic Usage of the setcookie() Function
To set a new Cookie in a user’s browser with PHP, you use the built-in function **setcookie()**.
This function generates the **HTTP header (Set-Cookie)**—in the aforementioned “From Server to Client” phase—which instructs the browser, “Please save this information.”
Basic Syntax and Required Arguments for setcookie()
The setcookie() function has various arguments depending on the information you want to set, but the two most important for basic usage are:
setcookie(name,value);
| Argument Position | Name | Description |
|---|---|---|
| 1 | name(名前) | The name used to identify the Cookie (Required) |
| 2 | value(値) | The data you want to store in the Cookie (Required) |
Practical Usage: Setting an Expiration Date
When setting a Cookie, an **expiration date (expire)** is usually set. Once the expiration date passes, the browser automatically deletes that Cookie.
The expiration date is specified as a **UNIX timestamp** (the number of seconds elapsed since January 1, 1970, 00:00:00 UTC). It is common practice to get the current timestamp using the `time()` function and add a number of seconds to specify a future time.
【Code Example】Setting a Cookie to be Valid for 1 Hour
<?php
// Cookie Name
$cookie_name = "user_preference";
// Value to store in the cookie
$cookie_value = "dark_mode_on";
// Expiration time: Current time (time()) + 3600 seconds (1 hour)
$expire_time = time() + (60 * 60);
// Set the cookie using the setcookie function
setcookie($cookie_name, $cookie_value, $expire_time);
// *Note: setcookie() must be executed before any HTML is sent to the browser.
// An error may occur if output such as echo or print_r is present before this.
?>
<!DOCTYPE html>
<html>
<head>
<title>Cookie Setting</title>
</head>
<body>
<?php
if (isset($_COOKIE[$cookie_name])) {
echo "<p>Cookie '{$cookie_name}' has been set.</p>";
}
?>
</body>
</html>
Point: There is a strict rule that **setcookie()** must be executed at the beginning of the page, **before any HTML output**. This is because the HTTP header, which carries the Cookie, is sent before the HTML body.
4. Retrieving and Using Cookies: Reading Stored Data
Data from Cookies saved in the user’s browser can be easily read within a PHP program using the **$_COOKIE** superglobal variable (a special variable accessible from anywhere in PHP).
Structure of the $_COOKIE Variable
$_COOKIE is in the form of an **associative array** (an array that holds data as key-value pairs). The array’s “key” corresponds to the Cookie’s name, and the “value” corresponds to the value stored in the Cookie.
| Cookie Name (Key) | Cookie Value (Value) |
|---|---|
| user_preference | dark_mode_on |
| user_id | 123 |
These can be accessed within a PHP program as follows:
// Example: Get the value with $_COOKIE['Cookie Name']
$preference = $_COOKIE['user_preference']; // 'dark_mode_on' is retrieved
$user_id = $_COOKIE['user_id']; // '123' is retrieved
Practical Usage: Checking if Data Exists
Since Cookies can be deleted by the user in their browser or expire, you must always check if the Cookie exists before using it.
Checking with the **isset()** function (a function that checks if a variable is set) is an iron rule in web development.
【Code Example】Checking for the Cookie’s existence and using it
<?php
// The name of the cookie to read
$cookie_name = "last_visit_time";
// Check if the cookie exists with isset()
if (isset($_COOKIE[$cookie_name])) {
// If the cookie exists, retrieve and use the value
$last_time = $_COOKIE[$cookie_name];
echo "<p>Your last visit: " . htmlspecialchars($last_time) . "</p>";
// Continue with processing, such as updating the cookie with the current time
// setcookie($cookie_name, date('Y-m-d H:i:s'), time() + (60 * 60 * 24 * 30));
} else {
// If the cookie does not exist (e.g., first visit)
echo "<p>Welcome! Thank you for visiting.</p>";
// Set the cookie for the first visit
// setcookie($cookie_name, date('Y-m-d H:i:s'), time() + (60 * 60 * 24 * 30));
}
?>
Point: Escaping the retrieved Cookie value with **htmlspecialchars()** or similar before outputting it to HTML can mitigate security risks (XSS attacks).
5. How to Delete Cookies and the Procedure
When a Cookie’s role is finished (e.g., when a user logs out) or when you want to change its settings, you need to delete that Cookie.
There is no dedicated function in PHP for deleting Cookies. Instead, you use the **setcookie()** function and **set the expiration time to a past time**, which prompts the browser to recognize the Cookie as “expired” and delete it.
Specific Procedure for Deleting a Cookie
The procedure for deleting a Cookie is very simple: call setcookie() while satisfying the following two conditions:
- Cookie Name and Value: Specify the name of the Cookie you want to delete as the first argument. The value (the second argument) can simply be an empty string (`””`).
- Expiration Date: Set a time in the past (e.g., `time() – 3600`) as the third argument.
【Code Example】Deleting a Cookie
<?php
// The name of the cookie to delete
$cookie_name = "user_preference";
// 1. Set the value of setcookie() to empty
// 2. Set the expiration time to the past (e.g., 1 hour ago)
setcookie($cookie_name, "", time() - 3600);
// Check if the cookie has been deleted
if (!isset($_COOKIE[$cookie_name])) {
echo "<p>Cookie '{$cookie_name}' has been deleted.</p>";
}
?>
Note: Just like when setting a Cookie, the setcookie() function must be executed before any output when deleting a Cookie.
Also, be aware that deletion may not occur correctly if the Cookie’s path, domain, or other arguments are not specified **exactly the same as when the Cookie was set (excluding the name and expiration)**.
6. Security and Precautions When Using Cookies
While Cookies are very convenient, they handle user personal information and session (login) details, so you must pay sufficient attention to security. We will explain the key points that web developers should be especially mindful of.
The “Secure” Attribute to Prevent Eavesdropping and Tampering
Cookies have attributes (optional arguments) that set constraints on how the Cookie is handled. Among these, the **Secure** attribute is crucial.
- Secure Attribute: When this attribute is set, the Cookie will only be transmitted over an **HTTPS connection** (an encrypted, secure connection).
// Example of setting the Secure attribute
// Set the 6th argument to true
setcookie("session_id", $id_value, $expire, "/", "example.com", true, true);
For Cookies handling **critical information (such as login details)**, always set the Secure attribute and ensure the entire site operates over HTTPS.
The “HttpOnly” Attribute for XSS Countermeasures
The **HttpOnly** attribute is one of the most effective ways to prevent Cookie theft through XSS (Cross-Site Scripting) attacks.
- HttpOnly Attribute: When this attribute is set, it becomes impossible for JavaScript to access the Cookie using methods like `document.cookie`.
Even if a malicious script is embedded, the inability to read the Cookie from JavaScript significantly reduces the risk of Session IDs or other secrets being exposed externally.
// Example of setting the HttpOnly attribute
// Set the 7th argument to true (the argument after the Secure attribute)
setcookie("session_id", $id_value, $expire, "/", "example.com", true, true);
Always set the **HttpOnly** attribute for Cookies that contain highly sensitive information, such as Session IDs.
Personal Data Protection and Cookie Policies
Regulations regarding the use of Cookies have been strengthened due to the influence of Japanese laws and regulations like the **GDPR (EU General Data Protection Regulation)**.
- Obtaining Consent: Before setting Cookies used for tracking or analyzing site visitors (such as third-party Cookies), you must obtain consent from the user.
- Clear Cookie Policy: You are required to provide a Cookie Policy page that clearly states what Cookies are used and for what purpose.
Compliance with these laws for Cookie operation is now the standard in modern web development to gain user trust.
7. PHP Sessions and Cookies: Differences and Key Usage Points
Both PHP Sessions and Cookies are used to maintain user state on a website, but they have major differences in where the data is stored and their purpose. Appropriately distinguishing between them leads to more secure and efficient web application development.
The Decisive Difference Between Sessions and Cookies
| Item | Cookie (クッキー) | Session (セッション) |
|---|---|---|
| Data Storage Location | Client side (user’s browser) | Server side (Web server) |
| Storable Data | Login ID, settings, tracking information, etc. (Small amount) | Login status, user information, access permissions, etc. (Virtually no capacity limit) |
| Security | Data is visible to the client, making it unsuitable for storing confidential information | Data is on the server, making it suitable for storing confidential information |
| Expiration | The duration set by `setcookie()` (Days to years) | Generally until the browser is closed (Session Cookie) |
Session Mechanism and the Role of Cookies
Sessions fundamentally operate with the following mechanism:
- When a user accesses the site, PHP generates user-specific session data on the server (e.g., logged in status) and issues a unique Session ID.
- Only this Session ID is stored as a Cookie in the user’s browser. (PHP usually handles this automatically.)
- When the user accesses another page, the browser sends the Session ID Cookie back to the server.
- The server reads the server-side data corresponding to the received Session ID and identifies the user’s state.
In essence, the role of the Cookie in a Session is to carry the **”key (Session ID) to access the real data stored on the server.”**
Key Points for Differentiating Usage
| Purpose | Recommended Technology | Reason |
|---|---|---|
| Maintaining login status | Session | Confidential user information (login authenticity, permissions) should be managed securely on the server side. |
| Shopping cart contents | Session | Due to the potential for large data volume, server-side management is common. |
| User display settings | Cookie | Less critical information that doesn’t need server-side management, such as “dark mode” or “language settings,” should use Cookies. |
| Access analysis, tracking | Cookie | Cookies are essential as they are used to identify users across site visits. |
In conclusion, for security reasons, it is recommended to **not** directly store confidential or critical data other than the Session ID in a Cookie, but instead to manage it on the server side using PHP’s session functionality.