Search code examples
phpformsvalidation

Not displaying the .success element after submitting the form


On submitting the form, the value of the display property is not changing to "flex" and the one of the form is not changing to "none" when the $_SESSION(['success']) is true.

I tried removing the redirection to "index.php" at the end of the register() method. I tried changing the notation of the if statement at the start of the View.php that checks for a successful session

<?php
session_start();
if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
} else {
    $success = false;
}

if (isset($_SESSION['errors'])) {
    $errors = $_SESSION['errors'];
} else {
    $errors = [];
}

$display_form = $success ? 'none' : 'flex';
$display_success = $success ? 'flex' : 'none';


unset($_SESSION['success']);
unset($_SESSION['errors']);


?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://use.typekit.net/elw3okv.css" />
    <link rel="stylesheet" href="./assets/css/style.css" />
    <title>Register</title>
</head>

<body>
    <form style="display: <?php echo $display_form; ?>" action="index.php?action=register" method="POST" id="add-form">
        <h2>Account erstellen</h2>
        <div class="error-wrapper">
            <div class="gender-wrapper">
                <div>
                    <input checked id="male" type="radio" value="male" name="gender">
                    <label for="male">Mann</label>
                </div>
                <div>
                    <input id="female" type="radio" value="female" name="gender">
                    <label for="female">Frau</label>
                </div>
                <div>
                    <input id="other" type="radio" value="other" name="gender">
                    <label for="other">Sonstiges</label>
                </div>
            </div>
            <?php if (!empty($errors['gender'])) : ?>
            <?php foreach ($errors['gender'] as $errorMsg) : ?>
            <small class="error-msg"><?php echo $errorMsg; ?></small>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <div class="error-wrapper">
            <select name="experience" id="experience">
                <option value="">--Ihr Kochniveau--</option>
                <option selected value="beginner">Küchenhilfe</option>
                <option value="intermediate">Kochlehrling</option>
                <option value="advanced">Jungkoch</option>
                <option value="professional">Küchenchef</option>
            </select>
            <?php if (!empty($errors['experience'])) : ?>
            <?php foreach ($errors['experience'] as $errorMsg) : ?>
            <small class="error-msg"><?php echo $errorMsg; ?></small>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <label class="error-wrapper" for="username">
            <input value="username" placeholder="Benutzername" type="text" id="username" name="username" />
            <?php if (!empty($errors['username'])) : ?>
            <?php foreach ($errors['username'] as $errorMsg) : ?>
            <small class="error-msg"><?php echo $errorMsg; ?></small>
            <?php endforeach; ?>
            <?php endif; ?>
        </label>
        <label class="error-wrapper" for="email">
            <input value="example@gmail.com" placeholder="Email" id="email" type="text" name="email" />
            <?php if (!empty($errors['email'])) : ?>
            <?php foreach ($errors['email'] as $errorMsg) : ?>
            <small class="error-msg"><?php echo $errorMsg; ?></small>
            <?php endforeach; ?>
            <?php endif; ?>
        </label>
        <label class="error-wrapper" for="password">
            <input value="890()=uioUIO" placeholder="Passwort" id="password" type="password" name="password" />
            <?php if (!empty($errors['password'])) : ?>
            <?php foreach ($errors['password'] as $errorMsg) : ?>
            <small class="error-msg"><?php echo $errorMsg; ?></small>
            <?php endforeach; ?>
            <?php endif; ?>
        </label>
        <div class="error-wrapper">
            <div class="tos-wrapper">
                <input checked name="tos" id="tos" type="checkbox">
                <label for="tos">Hiermit bestätige ich, dass ich die <a href="#">AGBs</a> akzeptiere.</label>
            </div>
            <?php if (!empty($errors['tos'])) : ?>
            <?php foreach ($errors['tos'] as $errorMsg) : ?>
            <small class="error-msg"><?php echo $errorMsg; ?></small>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
        <button type="submit" value="register">Registrieren</button>
    </form>
    <div class="success" style="display: <?php echo $display_success; ?>">
        <h2 class="success-msg">Ihr Account wurde erstellt!<br>Herzlich Willkommen bei</h2>
        <img class="logo" src="./assets/svg/Logo.svg" alt="Dishare">
    </div>
</body>

</html>
<?php

class RegistrationController
{
    public function __construct()
    {
        session_start();
    }

    public function register(): void
    {

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $inputs = [
                'gender' => $_POST['gender'] ?? '',
                'experience' => $_POST['experience'] ?? '',
                'username' => $_POST['username'] ?? '',
                'email' => $_POST['email'] ?? '',
                'password' => $_POST['password'] ?? '',
                'tos' => $_POST['tos'] ?? false,
            ];

            $errors = ['gender' => [], 'experience' => [], 'username' => [], 'email' => [], 'password' => [], 'tos' => []];

            foreach ($inputs as $input => $value) {
                switch ($input) {
                    case 'gender':
                        $genders = ['male', 'female', 'other'];
                        if (!isset($value)) $errors['gender'][] = 'Geschlecht ist erforderlich.';
                        if (!in_array($value, $genders)) {
                            $errors['gender'][] = 'Geschlecht muss valide sein.';
                        }
                        break;
                    case 'experience':
                        $experiences = ['beginner', 'intermediate', 'advanced', 'professional'];
                        if (empty($value)) $errors['experience'][] = 'Kochniveau ist erforderlich.';
                        if (!in_array($value, $experiences)) {
                            $errors['experience'][] = 'Kochniveau muss valide sein.';
                        }
                        break;
                    case 'username':
                        if (empty($value)) {
                            $errors['username'][] = 'Benutzername ist erforderlich.';
                        }
                        if (strlen($value) < 4) {
                            $errors['username'][] = 'Benutzername muss mindestens 4 Zeichen lang sein.';
                        }
                        if (strlen($value) > 16) {
                            $errors['username'][] = 'Benutzername darf maximal 16 Zeichen lang sein.';
                        }
                        if (str_contains($value, ' ')) {
                            $errors['username'][] = 'Benutzername darf keine Leerzeichen enthalten.';
                        }
                        break;
                    case 'email':
                        if (empty($value)) {
                            $errors['email'][] = 'Email ist erforderlich.';
                        }
                        if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                            $errors['email'][] = 'Gültige Email erforderlich.';
                        }
                        break;
                    case 'password':
                        if (empty($value)) {
                            $errors['password'][] = 'Passwort ist erforderlich.';
                        }
                        if (strlen($value) < 4) {
                            $errors['password'][] = 'Passwort muss mindestens 4 Zeichen lang sein.';
                        }
                        if (strlen($value) > 16) {
                            $errors['password'][] = 'Passwort darf maximal 16 Zeichen lang sein.';
                        }
                        if (str_contains($value, ' ')) {
                            $errors['password'][] = 'Passwort darf keine Leerzeichen enthalten.';
                        }
                        if (!preg_match('/[A-Z]/', $value)) {
                            $errors['password'][] = 'Passwort muss mindestens einen Großbuchstaben enthalten.';
                        }
                        if (!preg_match('/[a-z]/', $value)) {
                            $errors['password'][] = 'Passwort muss mindestens einen Kleinbuchstaben enthalten.';
                        }
                        if (!preg_match('/[0-9]/', $value)) {
                            $errors['password'][] = 'Passwort muss mindestens eine Zahl enthalten.';
                        }
                        break;
                    case 'tos':
                        if (!$value) $errors['tos'][] = 'AGBs müssen akzeptiert werden.';
                        break;
                }
            }
            $_SESSION['errors'] = $errors;
            if (empty($errors)) {
                $_SESSION['success'] = true;
            } else {
                $_SESSION['success'] = false;
            }

            header('Location: index.php');
        }
    }

    public function show()
    {
        header('Location: RegistrationView.php');
    }
}
<?php

require_once "RegistrationController.php";

$action = isset($_GET['action']) ? $_GET['action'] : '';

$controller = new RegistrationController();

if ($action === 'register') {
    $controller->register();
    exit();
} else {
    $controller->show();
    exit();
}

Solution

  • $errors is not empty because it contains array keys.

    if (empty(array_filter($errors))) {
        $_SESSION['success'] = true;
    } else {
        $_SESSION['success'] = false;
    }
    

    This will return values of your array keys, so, if none are set, the array is empty

    Example: https://onlinephp.io/c/813dc5