<?php
session_start();
// Om användaren skickar in ett namn
if (isset($_POST['username']) && !empty($_POST['username'])) {
$username = $_POST['username'];
$_SESSION['username'] = $username;
// Skapa cookie som gäller i 1 minut (60 sek)
setcookie("username", $username, time() + 60, "/");
}
// Döda sessionen
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
session_destroy();
$_SESSION = [];
}
// Döda cookie
if (isset($_GET['action']) && $_GET['action'] == 'deletecookie') {
setcookie("username", "", time() - 3600, "/"); // gör den ogiltig
}
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>m03u03 Session & Cookie</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f9;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.container {
background: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
width: 450px;
}
h1 {
font-size: 22px;
}
h2 {
font-size: 18px;
color: #666;
}
p.red {
color: red;
}
input[type="text"] {
width: 100%;
padding: 8px;
margin: 10px 0;
border-radius: 4px;
border: 1px solid #ccc;
}
button {
background-color: purple;
color: white;
padding: 8px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
}
a {
display: block;
margin-top: 10px;
color: purple;
text-decoration: none;
}
</style>
</head>
<body>
<div class="container">
<h1>Lösningsförslag m03u03</h1>
<h2>Utskrift av innehåll i session & cookie</h2>
<p class="red">
Om du precis har lagrat ett namn så finns det i SESSIONEN men det kanske inte hann lagras som en COOKIE.<br>
Ladda gärna om sidan med länken längst ner.
</p>
<?php if (isset($_SESSION['username'])): ?>
<p>Sessionen innehåller: <strong><?php echo htmlspecialchars($_SESSION['username']); ?></strong></p>
<?php else: ?>
<p>Sessionen är tom, ingen användare lagrad.</p>
<?php endif; ?>
<?php if (isset($_COOKIE['username']) && !empty($_COOKIE['username'])): ?>
<p>Cookien innehåller: <strong><?php echo htmlspecialchars($_COOKIE['username']); ?></strong></p>
<?php else: ?>
<p>Cookien är tom, ingen information är lagrad.</p>
<?php endif; ?>
<form method="post">
<input type="text" name="username" placeholder="Ange namn"
value="<?php echo isset($_COOKIE['username']) ? htmlspecialchars($_COOKIE['username']) : ''; ?>">
<button type="submit">Lagra användarnamn</button>
</form>
<a href="?action=logout">Döda sessionen</a>
<a href="?action=deletecookie">Döda cookie</a>
<a href="?">Ladda om sida utan GET-anrop</a>
<a href="../../webserver.html" class="btn">Gå tillbaka till landningssidan</a>
</div>
</body>
</html>