The following files exists in this folder. Click to view.
m03u3.php69 lines UTF-8 Unix (LF) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
<?php
require_once "functions.php";
// Hantera session & cookies
if (isset($_GET['action'])) {
switch ($_GET['action']) {
case 'create_session':
if (isset($_POST['username'])) {
$_SESSION['name'] = sanitize($_POST['username']);
setcookie("username", sanitize($_POST['username']), time() + 3600);
}
break;
case 'kill_session':
session_unset();
session_destroy();
break;
case 'kill_cookie':
setcookie("username", "", time() - 3600);
break;
}
}
?>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="UTF-8">
<title>m03u03</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<main>
<h1>Lösningsförslag m03u03</h1>
<h2>Session & Cookie-status</h2>
<div class="info">
<p class="red">Obs: session lagras direkt, men cookien kan kräva omladdning.</p>
<?php if (isset($_SESSION['name'])): ?>
<p>Session: <strong><?= $_SESSION['name'] ?></strong></p>
<?php else: ?>
<p>Session är tom.</p>
<?php endif; ?>
<?php if (!empty($_COOKIE['username'])): ?>
<p>Cookie: <strong><?= sanitize($_COOKIE['username']) ?></strong></p>
<?php else: ?>
<p>Cookie är tom.</p>
<?php endif; ?>
</div>
<form action="?action=create_session" method="POST">
<label for="username">Ange namn:</label>
<input type="text" name="username" id="username"
value="<?= isset($_COOKIE['username']) ? sanitize($_COOKIE['username']) : '' ?>"
required>
<input type="submit" value="Lagra användarnamn">
</form>
<p><a href="?action=kill_session">Döda sessionen</a></p>
<p><a href="?action=kill_cookie">Döda cookie</a></p>
<p><a href="?">Ladda om sidan</a></p>
</main>
</body>
</html>