1. What is a Session? Explaining its Role on Websites
When you browse websites, you experience states such as “being logged in” or “having items remaining in your shopping cart.” The mechanism for temporarily holding this “state” is called **Session**.
HTTP (HyperText Transfer Protocol), the fundamental technology of the internet, inherently has a “stateless” nature, meaning it does not retain state. This means that once a server responds to a request, it immediately forgets the connection and does not remember previous communication content.
💡 Tip for Beginners: What is Statelessness?
Imagine a convenience store clerk. If you buy a rice ball in the morning and go again at noon, they won’t say, “Oh, you’re the morning person!” but will greet you with “Welcome (Nice to meet you).” This is **statelessness**.
However, if you show your “membership card,” they will recognize you as, “Oh, it’s our regular Mr. Tanaka.” This membership card system is a concept close to **session**.
In a real website, it is necessary to continuously manage “state,” such as logged-in users and cart information. Sessions are an essential technology to **compensate for the stateless nature** of HTTP and to **link (associate) and manage** a series of user operations. Understanding the role of sessions is indispensable, especially when learning **WEB Development Basics**.
Main Roles of Sessions on Websites
- Maintaining Login State (Holding Authentication Information): Maintains the state that “this person is logged in” across all pages after the user logs in with an ID and password.
- Shopping Cart Function: Temporarily holds product information and quantities selected by the user until the payment is completed.
- Saving User-Specific Settings: Temporarily saves personalized information, such as display settings or language settings within the site.
2. Session vs. Cookie: Understanding the Decisive Differences and When to Use Which
Both Sessions and Cookies are used to “maintain state,” but there is a decisive difference in **where the data is stored**. Understanding this difference enables safer and more efficient **PHP Web development**.
The Decisive Difference is “Data Storage Location”
| Item | Session | Cookie |
|---|---|---|
| Main Storage Location | Server-Side (Web server files or databases) | Client-Side (User’s Web browser) |
| Data Content | Arbitrary complex data (Login ID, cart information, etc.) | Mainly the **Session ID** issued by the server (Other, simple information) |
| Security | Managed on the server-side, hence **relatively safe** | Easily viewable/tamperable by the user, leading to **high security risk** |
| Capacity Limit | **Virtually unlimited** as long as server resources permit | Relatively strict limits apply (Generally up to 4KB) |
🔑 What if we compare it to a coin locker?
- Session (Locker Contents): The luggage (data) itself is safely stored inside the station locker (server).
- Cookie (Locker Key): The user only holds the “key with the locker number written on it (Session ID).” The key itself does not contain the luggage, but it allows the user to retrieve their belongings.
Key Points for Choosing Between Session and Cookie
- Cases Where Session Should Be Used: Used for highly confidential information and when security is required.
- Example: User authentication information while logged in, cart contents before payment, data including personal information.
- Cases Where Cookie Should Be Used: Used when you want to retain relatively simple and non-confidential information long-term on the user’s browser side.
- Example: Token for “Automatic Login Next Time,” previously viewed product history, site theme color settings (like dark mode).
3. Session Mechanism: Where is the Data Stored and How is it Managed?
The session mechanism works by exchanging a unique key called the “Session ID” between the browser and the server. This **Session ID** serves as the marker to identify a specific user’s information from the massive amount of user data stored on the server side.
Flow from Session Start to End
- Session Start (Server-Side): When a user accesses a website and performs a process requiring a session (e.g., login), the server generates a random string called the **Session ID**.
- Session Data Storage (Server-Side): The server uses the generated Session ID as a key (identifier) and saves the user’s data (e.g., User ID) in a **session file** or database.
- Session ID Issuance (To Client-Side): The server sends the generated Session ID as a Cookie to the user’s Web browser.
- Data Retrieval Cooperation (Browser → Server): When the user transitions to another page, the browser automatically includes the stored Session ID (Cookie) in the request and sends it to the server.
- Data Matching and Usage (Server-Side): The server uses the received Session ID to identify the corresponding user’s data from the session file and uses it for processing.
Where Session Data is Stored
In **PHP’s session mechanism**, by default, data is stored as **temporary files (session files)** within the Web server. This storage location can be checked and changed in the php.ini configuration item called session.save_path. For large-scale sites, it may also be stored in an in-memory database like Redis for high-speed data processing.
4. Basic Steps and Configuration for Using Sessions in PHP
In **PHP**, one of the most frequently used languages in web development, sessions can be handled very easily. However, to use sessions, the session_start() function must be called **before any process** that reads or writes data. This is the basic procedure for using sessions in PHP.
`session_start()` Function is Required Before All Session Operations
The session_start() function is the “magic phrase” required for PHP to perform initial preparations such as sending and receiving the Session ID and loading data from the server-side session file.
[Important] session_start() must be executed **before any output**, including HTML tags or whitespace. If you try to execute it after output, an error like “Headers already sent” will occur, preventing the Session ID from being sent to the browser.
<?php
// ⭕️ Correct Way: Write before outputting HTML, etc.
session_start();
?>
<!DOCTYPE html>
<html>
<head>...</head>
<body>...</body>
</html>
Key `php.ini` Settings Related to Sessions
Key settings related to **PHP Session Usage** are managed in the overall Web server configuration file, php.ini. Usually, it works without issue with default settings on shared hosting, but it’s good to know the concept.
session.save_path: Specifies the directory (folder) on the server where session data is stored.session.name: Specifies the name of the Cookie that stores the Session ID. Changing it from the defaultPHPSESSIDis sometimes recommended for security reasons.
5. Specific Code Examples for Session Data Registration, Retrieval, and Deletion
In PHP, session data is manipulated using the special **superglobal variable** $_SESSION (a variable accessible from anywhere in the PHP script) as an array.
Data Registration (Writing) / Update
You can register (save) data to a session by assigning a key (identification name) and a value to the $_SESSION variable.
<?php
session_start();
// Save 'Taro' with the key 'username'
$_SESSION['username'] = 'Taro';
// Save a count with the key 'cart_items'
$_SESSION['cart_items'] = 3;
echo 'Data saved to session.';
?>
Data Retrieval (Reading)
Retrieve the value using the same key as registration. It is common to check with the isset() function (a function to check if a variable is set) to avoid errors if the key does not exist.
<?php
session_start();
// Display after checking if data is saved
if (isset($_SESSION['username'])) {
echo 'Welcome, ' . $_SESSION['username'] . '!';
} else {
echo 'Not logged in.';
}
?>
Session Data Deletion (Specific Data / All Data)
For session data, there are methods to delete only specific values and methods to destroy the entire session.
- Deleting a specific key (
unset): Use theunset()function to delete only a specific key from the$_SESSIONarray. - Destroying the entire session (
session_destroy): Used when a user logs out, etc., to destroy the entire session from the server side and invalidate the Session ID.
<?php
session_start();
// 1. When deleting only specific data (e.g., emptying only the cart contents)
unset($_SESSION['cart_items']);
// 2. Steps to completely erase the session, such as upon logout
$_SESSION = array(); // Empty the session variables in memory
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() - 42000, '/'); // Also delete the Cookie
}
session_destroy(); // Destroy the server-side session file
echo 'Logged out.';
?>
6. Causes of Session Expiry (Timeout) and How to Change the Time
Sessions always have an **expiration date** for security reasons. When this expiration date passes, or when the Session ID expires due to a specific cause, the session expires (timeouts), and a re-login state is required.
Main Causes of Session Timeout
Session timeout is mainly related to two factors: the **server-side session expiration** and the **client-side Cookie expiration**.
- Server-Side Expiration: This occurs when session data stored on the server is automatically deleted (garbage collection) if there is no access for a certain period.
- Session Cookie Expiration: This occurs when the Cookie storing the Session ID in the browser expires or the browser is closed, preventing the Session ID from being sent to the server.
How to Change Session Expiration
To change the **PHP Session Timeout**, adjust the server-side configuration (php.ini).
; php.ini configuration example
; 1. Server-side storage duration (seconds)
; Default is 1440 seconds (24 minutes). For example, to set it to 1 day:
session.gc_maxlifetime = 86400
; 2. Cookie expiration duration
; 0 means it ends when the browser is closed. To keep it for 1 day:
session.cookie_lifetime = 86400
7. Security Measures and Precautions When Using Sessions
If a Session ID is leaked, there is a risk that it could be used for serious security attacks such as **session hijacking**. Let’s understand the essential security measures for building a secure website.
Session Hijacking Countermeasures: Preventing Session ID Leakage
Session hijacking is the act of an attacker somehow stealing the Session ID of a legitimate user and impersonating that user to use the service.
- Set the
HttpOnlyattribute on the Cookie (Required)
Setting theHttpOnlyattribute prohibits JavaScript from accessing the Cookie (Session ID). This prevents the Session ID from being stolen by XSS (Cross-Site Scripting) attacks.
How to set: Setsession.cookie_httponlyinphp.inito1. - Set the
Secureattribute on the Cookie (Required in HTTPS environment)
Setting theSecureattribute ensures the Cookie is only sent during an SSL/TLS (HTTPS) connection. This significantly reduces the risk of the Session ID being eavesdropped on during communication.
How to set: Setsession.cookie_secureinphp.inito1.
Session Fixation Countermeasures: Always Regenerate Session ID After Login
Session fixation is an attack where an attacker forces a user to use a specific Session ID, which is then stolen during the subsequent login.
- Execute
session_regenerate_id(true)after login completion (Required)
Immediately after the user completes authentication (login), regenerating the Session ID to a new one invalidates the previously used Session ID.
<?php
session_start();
// ... User ID and password check process ...
if ($login_success) {
// [IMPORTANT] Re-assign a new Session ID immediately after successful login!
// Specifying true deletes the old session file
session_regenerate_id(true);
$_SESSION['user_id'] = $user_id;
echo 'Logged in.';
}
?>