Cookies and sessions are two fundamental concepts in web development that help manage user state and data across multiple requests. Understanding how they work and when to use each is crucial for building effective web applications.
Cookies are temporary storage on client browser
Server uses it store information
Request/response is stateless. So you need a mechanism to save state.
Little breadcrumnbs/cookies to save state
<?php
// Note - cannot have any output before setcookie
if (! isset($_COOKIE['var_cookie']) ){
setcookie('var_cookie', '23', time() + 4000);
}
print_r($_COOKIE);
?>
Make state persist across request response cycles
Shopping cart or login information stored in sessions
A large random number that is hard to guess. Stored as key value pairs
If you find out the number you can get access
session_start()
can now store value in $_SESSION variable
session_destroy()

login.html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<form action="login.php" method="POST">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
login.php<?php
session_start();
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if ($username === 'admin' && $password === 'password12') {
$_SESSION['login'] = true;
header('Location: welcome.php');
exit();
} else {
$error = "Invalid username or password.";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h1>Login</h1>
<?php if (isset($error)): ?>
<p style="color: red;"><?php echo $error; ?></p>
<?php endif; ?>
<form action="login.php" method="POST">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
welcome.php<?php
session_start();
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
header('Location: login.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Welcome, admin!</h1>
<p>You are logged in. The session variable <code>$_SESSION['login']</code> is set to <strong>true</strong>.</p>
<a href="logout.php">Logout</a>
</body>
</html>
logout.php<?php
session_start();
session_destroy();
header('Location: login.php');
exit();
?>
<?php
// Note - no output before this
session_start();
if ( !isset($_SESSION['value']) ){
$_SESSION['value'] = 0;
} else {
session_destroy();
session_start();
}
?>
<p>
< a href = "sessfun.php"> Click me
</a>
</p>
<pre>
<?php
print_r($_SESSION['value']);
?>
</pre>
Using hidden to send session ID.