View sourcecode

The following files exists in this folder. Click to view.

m03u3.php

69 lines UTF-8 Unix (LF)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?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>