Källkod

Välj en PHP-fil för att visa dess källkod.

exercises/uppg5.php

<?php
require __DIR__ . '/../incl/config.php';
session_start();
error_reporting(-1);
ini_set('display_errors', '1');

function 
h($value)
{
    return 
htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

// Enkelt lösenord för skoluppgiften. Byt det vid behov; detta är inte ett produktionsskydd.
$quizPassword = 'quiz123';
$gateError = '';

if (isset(
$_GET['nytt'])) {
    unset(
$_SESSION['uppg5']);
    
header('Location: uppg5.php');
    exit;
}

if (
$_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'unlock') {
    
$enteredPassword = (string)($_POST['password'] ?? '');
    if (
hash_equals($quizPassword, $enteredPassword)) {
        
$_SESSION['quiz_unlocked'] = true;
    } else {
        
$gateError = 'Lösenordet stämde inte. Försök igen.';
    }
}

$baseUrl = '../';
$title = 'Frågetävling – uppgift 5';

if (empty(
$_SESSION['quiz_unlocked'])) {
    require 
__DIR__ . '/../incl/header.php';
    
?>
    <section class="quiz-card">
        <h1>Frågetävling – lösenord krävs</h1>
        <p>Ange lösenordet för att öppna frågorna.</p>
        <?php if ($gateError !== ''): ?><p class="error"><?= h($gateError) ?></p><?php endif; ?>
        <form method="post">
            <label for="password">Lösenord
                <input id="password" type="password" name="password" required>
            </label>
            <button type="submit" name="action" value="unlock">Öppna frågetävlingen</button>
        </form>
    </section>
    <?php
    
require __DIR__ . '/../incl/footer.php';
    exit;
}

$questions = [
    [
        
'question' => 'Vilket språk körs på webbservern i den här kursen?',
        
'answers' => ['a' => 'PHP', 'b' => 'CSS', 'c' => 'HTML', 'd' => 'PNG'],
        
'correct' => 'a',
    ],
    [
        
'question' => 'Vilken superglobal används för formulär som skickas med POST?',
        
'answers' => ['a' => '$_GET', 'b' => '$_POST', 'c' => '$_FILES', 'd' => '$_COOKIE'],
        
'correct' => 'b',
    ],
    [
        
'question' => 'Vilken funktion hjälper till att visa användartext säkert i HTML?',
        
'answers' => ['a' => 'array_sum()', 'b' => 'mail()', 'c' => 'htmlspecialchars()', 'd' => 'sort()'],
        
'correct' => 'c',
    ],
];

$quizState = $_SESSION['uppg5'] ?? [
    
'step' => 1,
    
'name' => '',
    
'email' => '',
    
'email_opt_in' => false,
    
'answers' => [1 => '', 2 => '', 3 => ''],
    
'finished' => false,
    
'score' => 0,
    
'email_status' => '',
];
$errors = [];

if (
$_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'answer' && empty($quizState['finished'])) {
    
$step = (int)$quizState['step'];

    if (
$step === 1) {
        
$quizState['name'] = trim((string)($_POST['name'] ?? ''));
        
$quizState['email'] = trim((string)($_POST['email'] ?? ''));
        
$quizState['email_opt_in'] = isset($_POST['email_opt_in']);
        if (
$quizState['name'] === '') {
            
$errors[] = 'Skriv ditt namn innan du fortsätter.';
        }
        if (
$quizState['email_opt_in'] && !filter_var($quizState['email'], FILTER_VALIDATE_EMAIL)) {
            
$errors[] = 'Skriv en giltig e-postadress eller avmarkera mejlvalet.';
        }
    }

    
$choice = trim((string)($_POST['answer'] ?? ''));
    if (!
array_key_exists($choice, $questions[$step - 1]['answers'])) {
        
$errors[] = 'Välj ett av svarsalternativen.';
    }

    if (!
$errors) {
        
$quizState['answers'][$step] = $choice;
        if (
$step < count($questions)) {
            
$quizState['step']++;
        } else {
            foreach (
$questions as $index => $question) {
                if (
$quizState['answers'][$index + 1] === $question['correct']) {
                    
$quizState['score']++;
                }
            }

            if (
$quizState['email_opt_in']) {
                
$message = "Hej " . $quizState['name'] . "!\n\nDu fick " . $quizState['score'] . " av " . count($questions) . " rätt i frågetävlingen.";
                if (
mail($quizState['email'], 'Ditt resultat i frågetävlingen', $message)) {
                    
$quizState['email_status'] = 'Resultatet har skickats till din e-postadress.';
                } else {
                    
$quizState['email_status'] = 'Resultatet kunde inte mejlas från den här servern.';
                }
            }

            
$quizState['finished'] = true;
        }
    }

    
$_SESSION['uppg5'] = $quizState;
}

$step = (int)$quizState['step'];
$name = $quizState['name'];
$email = $quizState['email'];
$emailOptIn = $quizState['email_opt_in'];
$answers = $quizState['answers'];
$finished = $quizState['finished'];
$score = $quizState['score'];
$emailStatus = $quizState['email_status'];

require 
__DIR__ . '/../incl/header.php';
?>
<section class="quiz-card">
    <h1>Frågetävling</h1>
    <p>Svara på tre frågor. Bara en fråga visas åt gången.</p>

    <?php if ($errors): ?>
        <p class="error"><?= h(implode(' ', $errors)) ?></p>
    <?php endif; ?>

    <?php if ($finished): ?>
        <h2>Resultat</h2>
        <p><?= h($name) ?> fick <strong><?= $score ?> av <?= count($questions) ?></strong> rätt.</p>
        <?php if ($emailStatus !== ''): ?><p><?= h($emailStatus) ?></p><?php endif; ?>

        <h2>Genomgång av svaren</h2>
        <?php foreach ($questions as $index => $question): ?>
            <?php $questionNumber = $index + 1; ?>
            <section class="card">
                <h3>Fråga <?= $questionNumber ?>: <?= h($question['question']) ?></h3>
                <?php foreach ($question['answers'] as $key => $label): ?>
                    <?php
                    $answerClass 
= '';
                    if (
$key === $question['correct']) {
                        
$answerClass = 'answer-correct';
                    } elseif (
$key === $answers[$questionNumber]) {
                        
$answerClass = 'answer-wrong';
                    }
                    
?>
                    <p class="<?= h($answerClass) ?>">
                        <?= h($label) ?>
                        <?php if ($key === $question['correct']): ?> — rätt svar<?php endif; ?>
                        <?php if ($key === $answers[$questionNumber] && $key !== $question['correct']): ?> — ditt svar<?php endif; ?>
                    </p>
                <?php endforeach; ?>
            </section>
        <?php endforeach; ?>
        <a class="button" href="uppg5.php?nytt=1">Spela igen</a>
    <?php else: ?>
        <h2>Fråga <?= $step ?> av <?= count($questions) ?></h2>
        <form method="post">
            <?php if ($step === 1): ?>
                <label for="name">Ditt namn
                    <input id="name" type="text" name="name" value="<?= h($name) ?>" required>
                </label>
                <label>
                    <input type="checkbox" name="email_opt_in" value="yes" <?= $emailOptIn ? 'checked' : '' ?>>
                    Mejla gärna mitt resultat
                </label>
                <label for="email">E-postadress (valfri)
                    <input id="email" type="email" name="email" value="<?= h($email) ?>">
                </label>
            <?php endif; ?>

            <p><?= h($questions[$step - 1]['question']) ?></p>
            <?php foreach ($questions[$step - 1]['answers'] as $key => $label): ?>
                <label>
                    <input type="radio" name="answer" value="<?= h($key) ?>" required>
                    <?= h($label) ?>
                </label>
            <?php endforeach; ?>
            <button type="submit" name="action" value="answer">Nästa</button>
        </form>
    <?php endif; ?>
</section>
<?php require __DIR__ . '/../incl/footer.php'; ?>