Sessions-Cookies & Security
What is a session? session_start()
A session in PHP is a method through which the server stores information about a user during their visit (or across multiple visits) to a web application. This way, data is preserved even if the user navigates between several pages.
Unlike cookies (which are stored on the user's computer), session data is stored on the
server and identified by a unique session ID, sent back to the user as a small cookie (usually
PHPSESSID).
Starting a session
To start a session in PHP, we use the session_start() function. This must always be placed at the
very beginning of the PHP script, before any HTML output.
<?php
// Start the session
session_start();
// Store a value in the session
$_SESSION["username"] = "John Smith";
echo "The session has started and we saved username = " . $_SESSION["username"];
?>
In the example above, we created a session and stored a username field. This allows the
information to be available on all pages where we call session_start().
Storing data in a session
Once we start the session with session_start(), we can save and access global variables using the
$_SESSION superglobal. These variables remain available throughout the session, regardless of the
page.
Example: Saving and reading session variables
<?php
session_start(); // start the session
// Save data in the session
$_SESSION["username"] = "Mary Ionella";
$_SESSION["email"] = "maria@example.com";
$_SESSION["role"] = "administrator";
// Read data from the session
echo "Welcome, " . $_SESSION["username"] . "!<br>";
echo "Email: " . $_SESSION["email"] . "<br>";
echo "Role: " . $_SESSION["role"] . "<br>";
?>
Note: these variables will be available in any other PHP page where we call session_start(). For
example, if we have a profile.php page, we can display the user's data directly from the session.
Example: Accessing session data on another page
<?php
session_start(); // the session must be started on every page
if (isset($_SESSION["username"])) {
echo "Hello from profile, " . $_SESSION["username"] . "!";
} else {
echo "No user is logged in.";
}
?>
This way we can build a simple login system: once the user authenticates, their data is stored in the session and accessible on all site pages.
Creating and reading cookies
Cookies are small files stored on the user's computer. They keep information even after the session has ended
(unlike $_SESSION, which disappears when the browser is closed).
Setting a cookie
To create a cookie, we use the setcookie() function. A cookie has a name, value, expiration time,
and optionally other attributes (path, domain, security).
<?php
// Create a "username" cookie valid for 1 hour
setcookie("username", "Mary", time() + 3600, "/");
// Create a "preferences" cookie valid for 1 day
setcookie("preferinte", "dark-mode", time() + 86400, "/");
?>
Reading a cookie
Cookies can be accessed with the $_COOKIE superglobal.
<?php
if (isset($_COOKIE["username"])) {
echo "Welcome, " . $_COOKIE["username"];
} else {
echo "No user cookie found.";
}
?>
Practical example
We can use cookies to remember a visitor's preferences (for example, the selected theme).
<?php
// If the user chooses the "dark" theme, save it in a cookie
if (isset($_GET["theme"])) {
$theme = $_GET["theme"];
setcookie("theme", $theme, time() + 86400, "/"); // valid for 1 day
echo "You selected theme: $theme";
}
// On each visit, check the cookie
if (isset($_COOKIE["theme"])) {
echo "<br>Saved theme is: " . $_COOKIE["theme"];
}
?>
<a href="?theme=light">Light Theme</a> |
<a href="?theme=dark">Dark Theme</a>
This way, even if the user closes the browser, the theme preference will be remembered on their next visit.
Deleting Cookies
A cookie cannot be “deleted” directly from PHP. To remove it, you must overwrite it with an expiration date in the past.
Simple Example
<?php
// We delete the "username" cookie
setcookie("username", "", time() - 3600, "/");
echo "The 'username' cookie has been deleted.";
?>
Practical Example with Check
<?php
// If the user clicks "Logout", we delete the cookie
if (isset($_GET["logout"])) {
setcookie("username", "", time() - 3600, "/");
echo "You have logged out. The cookie has been deleted.";
} else {
if (isset($_COOKIE["username"])) {
echo "Welcome back, " . $_COOKIE["username"];
echo "<br><a href='?logout=1'>Logout</a>";
} else {
echo "No active cookie exists.";
}
}
?>
Thus, the username cookie is removed when the user clicks the logout button or when the initially
set expiration time passes.
Password Hashing (password_hash, password_verify)
Passwords should NEVER be stored in plain text in the database. Instead, we use the functions
password_hash() and password_verify() to secure the data.
Creating a Hash for a Password
<?php
// Example: user enters a password
$parola = "secret123";
// Generate a secure hash
$hash = password_hash($parola, PASSWORD_DEFAULT);
echo "Generated hash: " . $hash;
?>
Verifying a Password
<?php
$password_entered = "secret123"; // password entered at login
$hash_saved = '$2y$10$eImiTXuWVxfM37uY4JANjQ=='; // example hash from DB
if (password_verify($password_entered, $hash_saved)) {
echo "✅ Password is correct!";
} else {
echo "❌ Incorrect password!";
}
?>
Explanations
password_hash()uses the Bcrypt or Argon2 algorithm, depending on the PHP version.password_verify()compares the entered password with the hash from the database.- The hash is unique each time (due to the “salt”), but verification works correctly.
CSRF Protection & session_id Regeneration
CSRF (Cross-Site Request Forgery) is an attack where an authenticated user is tricked into sending unintended
requests to the server. To prevent this type of attack, we use CSRF tokens and periodically
regenerate session_id().
Generating and Using a CSRF Token
<?php
session_start();
// If the token doesn't exist, create it
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
<form method="post" action="process.php">
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
<input type="text" name="comment" placeholder="Write a comment">
<button type="submit">Submit</button>
</form>
Token Validation
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
die("❌ CSRF attack detected!");
}
echo "✅ Valid request. Comment has been submitted.";
}
?>
Regenerating session_id()
<?php
session_start();
// Regenerate the session ID after login
if (!isset($_SESSION['logged_in'])) {
$_SESSION['logged_in'] = true;
session_regenerate_id(true); // deletes old ID and creates a new one
echo "Session ID regenerated for security.";
}
?>
Explanations
bin2hex(random_bytes(32))→ generates a secure and unique token for each session.- The token is placed in the form as a
hidden input. - When the form is submitted, we check if the token from
POSTmatches the one in the session. session_regenerate_id(true)protects against Session Fixation attacks.
Practical Example: Simple Login with Sessions
This example demonstrates a simple and secure authentication flow in PHP. Input data is checked, the password is hashed, and after authentication, the user session is created.
Login Form (ex-login.php)
<?php session_start(); ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Simple Login</h2>
<?php if (isset($_SESSION['error'])): ?>
<p style="color:red;"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></p>
<?php endif; ?>
<form method="POST" action="ex-login_process.php">
<label>Username: <input type="text" name="username"></label><br><br>
<label>Password: <input type="password" name="password"></label><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Processing Login (ex-login_process.php)
<?php
session_start();
// Example only (in reality, check DB + password_verify)
$validUser = "admin";
$validPass = "1234";
if ($_POST['username'] === $validUser && $_POST['password'] === $validPass) {
$_SESSION['user'] = $validUser;
header("Location: ex-dashboard.php");
exit;
} else {
$_SESSION['error'] = "Invalid login credentials!";
header("Location: ex-login.php");
exit;
}
?>
Profile Page (ex-dashboard.php)
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("Location: ex-login.php");
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
</head>
<body>
<h2>Welcome, <?php echo htmlspecialchars($_SESSION['user']); ?>!</h2>
<p>This is a protected area.</p>
<a href="ex-logout.php">Logout</a>
</body>
</html>
Logout (logout.php)
<?php
session_start();
session_unset();
session_destroy();
header("Location: ex-login.php");
exit;
?>
Login Example. Click the link to see the live example.
User: admin
Password: 1234