V
V
vovkka2018-04-04 17:51:47
PHP
vovkka, 2018-04-04 17:51:47

How to properly organize the storage of errors in the session?

Good afternoon. When processing forms on different pages, errors are accumulated in the $errors array. Also, upon successful registration, etc., messages are accumulated in the $successMessage array.
The question is how to correctly save errors to the session for subsequent output on the same page or on others when redirecting. Now I did it like this:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["name"])) {
        $errors[] = "Заполните имя!";
    }

    if (empty($_POST["age"])) {
        $errors[] = "Заполните возраст!";
    }

    $_SESSION["errors_forms"] = $errors;

    if (count($errors) === 0) {
      $successMessage[] = "Форма успешно отправленна!";
      $_SESSION["success_forms"] = $successMessage;
      header("Location: obr_form.php");
      exit();
    }
}

How would you do? All the best!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-04-04
@By_Engine

$errs = [];
if(isset($_SESSION['errors_form'])){
$errs = $_SESSION['errors_form'];
unset($_SESSION['errors_form']);
}

A
Arman, 2018-04-04
@Arik

It makes no sense to store further than one redirection, as an option, you can clear the records when you display them. Have experience with storage

<?php 
$_SESSION['alerts'] = [
    [
    'type' => 'success',
    'message' => 'Форма отправлена',
    'namespace' => 'form2',
    ],
];
?>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question