Understanding Cookies and Sessions in PHP: A Beginner's Guide

![[PHP 강의] PHP 8.4 웹 프로그래밍 강의를 시작하며 – 초보도 끝까지 완주할 수 있는 실전 강의](/uploads/editor/PHP-%EA%B0%95%EC%9D%98-PHP-8-4-%EC%9B%B9-%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D-%EA%B0%95%EC%9D%98%EB%A5%BC-%EC%8B%9C%EC%9E%91%ED%95%98%EB%A9%B0-%EC%B4%88%EB%B3%B4%EB%8F%84-%EB%81%9D%EA%B9%8C%EC%A7%80-%EC%99%84%EC%A3%BC%ED%95%A0-%EC%88%98-%EC%9E%88%EB%8A%94-%EC%8B%A4%EC%A0%84-%EA%B0%95%EC%9D%98-20260702-5787b7.webp)
HTTP Is Stateless
When you visit a website, your browser sends a request to the server and receives a response.
However, HTTP is a stateless protocol, meaning it does not remember previous interactions.
In other words, every time you request a new page, the server treats it as a new user session.
For example:
Login status
Shopping cart contents
Recently viewed posts
Dar mode settings
These details are not preserved by default.
To solve this problem, developers use cookies and sessions.
What Are Cookies?
Cookies are small pieces of data stored in the user's browser.
When a server requests a cookie to be saved, the browser stores it and sends it back with future requests.
For example:
Remembering usernames
Automatic login
Language preferences
Theme settings
These are common uses for cookies.
Creating a Cookie
In PHP, you use the setcookie() function to create a cookie.
<?php
setcookie(
"username",
"Hong Gildong",
time() + 3600
);
The third parameter specifies the cookie's expiration time.
In this example, the cookie lasts for one hour.
Reading a Cookie
Saved cookies can be accessed via the $_COOKIE array.
<?php
echo $_COOKIE["username"];
Output:
Hong Gildong
Deleting a Cookie
To delete a cookie, set its expiration time to a past date.
<?php
setcookie(
"username",
"",
time() - 3600
);
The browser automatically removes the cookie.
Where Are Cookies Stored?
Cookies are stored in the user's browser, not on the server.
This means users can delete or modify them directly.
Important information should not be stored in cookies.
What Are Sessions?
Sessions store user data on the server.
The browser only stores a session ID, while the actual data remains on the server.
Login functionality typically uses sessions.
Starting a Session
To use sessions, you must first call session_start().
<?php
session_start();
This must be executed before any HTML output.
Storing Session Data
<?php
session_start();
$_SESSION["username"] = "Hong Gildong";
Reading Session Data
<?php
session_start();
echo $_SESSION["username"];
Output:
Hong Gildong
Deleting a Session
To delete specific session data:
<?php
session_start();
unset($_SESSION["username"]);
Destroying All Sessions
This is commonly used during logout:
<?php
session_start();
session_destroy();
All session data is removed.
Cookies vs. Sessions
Cookie | Session |
|---|---|
Browsed stored | Served stored |
User can modify | Hard to modify |
Limited storage space | More flexible storage |
Faster speed | Better security |
When to Use Cookies
Cookies are suitable for storing non-sensitive information.
Examples include:
Remembering usernames
Automatic login preference
Recently viewed posts
Language selection
Dark mode settings
This is common practice in web development.
When to Use Sessions
Sessions are used for storing sensitive user information.
Examples include:
Login status
User ID
Admin privileges
Shopping cart contents
Payment details
In practice, most login systems rely on sessions.
Login Example
After a successful login, store the session:
<?php
session_start();
$_SESSION["userid"] = "admin";
echo "Login completed";
Checking Login Status
<?php
session_start();
if (isset($_SESSION["userid"])) {
echo "You are logged in.";
}
else {
echo "Login required.";
}
Creating a Logout Function
<?php
session_start();
session_destroy();
echo "Logged out.";
This approach is widely used in forums and other platforms.
Checking Admin Privileges
<?php
session_start();
if ($_SESSION["userid"] == "admin") {
echo "You are an admin.";
}
This method is frequently used for post deletion and user management.
Using Cookies and Sessions Together
In practice, both features are often combined:
Cookies:
Automatic login preference
Usernames
Sessions:
Login status
User ID
Permissions
This leverages the strengths of both technologies.
Why Sessions Persist
The browser stores the session ID as a cookie, allowing the server to identify users across pages.
This is why login status remains intact when navigating to new pages.
Common Beginner Mistakes
New learners often make these errors:
Forgetting to write
session_start().Calling
session_start()after HTML output.Not using
session_destroy()during logout.Mixing up cookies and sessions.
Storing sensitive data in cookies.
Focusing on these points can prevent many common issues.
Practical Example
Let's create a simple login persistence feature:
<?php
session_start();
if (isset($_POST["userid"])) {
$_SESSION["userid"] = $_POST["userid"];
}
if (isset($_SESSION["userid"])) {
echo "Current logged-in user: ";
echo $_SESSION["userid"];
}
else {
echo "Login required.";
}
This example mirrors the basic structure of a real login system (without database integration).
Next, we'll connect to a database to build a fully functional login feature.
How Forums Use These Features
In upcoming forum projects, sessions will be used for:
Login persistence
Author verification
Admin privilege checks
Edit permissions
Delete permissions
Cookies will be used for:
Username persistence
Recently viewed posts
User preference storage
Understanding these concepts makes building forums significantly easier.
In Conclusion
This lesson covered the concepts and usage of cookies and sessions.
Cookies and sessions are essential for implementing login functionality in web development.
Specifically, sessions will be heavily used in future forum and user management projects, so mastering them is crucial.
In the next lesson, we'll learn how to structure projects using include and require, enabling efficient file management in real-world scenarios.
FAQ
What is the main difference between cookies and sessions?
Cookies store data on the user's browser, while sessions store data on the server. Cookies are accessible by users, but session data remains secure on the server.
When should I use cookies instead of sessions?
Use cookies for non-sensitive information like language preferences or theme settings. Use sessions for sensitive data such as login status and user IDs.
Korean Source
This article is an English localization of a Korean-language report from BlogScore. Original: [PHP 강좌] 7강 쿠키(Cookie)와 세션(Session) 이해하기