Hello! On the registration page, the following is implemented: when checking the form, various checks take place, after which the data in the filled fields disappeared. With the help of the session variable, this was avoided, the data is saved in the fields, but if the user navigates to another page of the site and then returns to the registration, the data will still remain there. How can I fix this - so that after the user closes the registration page, the session variable is also deleted.

    4 answers 4

    BY GOOD
    The approach is fundamentally wrong, why for each bunch to load the server with unnecessary operations. Here you have started the registration process -> the user enters a name for example, mail, something else -> You check it on the front with JS for validity, if there are fields for example a login that must be unique-> then ajax request to the server is done with the purpose is to find out there is no-> found out, all is good and you want to start registering on the server, knowing that the data is suitable-> then ajax request is sent to the server in order to register-> server just in case in its own way checked everything -> if all the good was recorded in the session the necessary data if required-> returned to the front that all the gu -> and move on, or the reason that it is not so -> the front and decided to open the next page or not, and an error.

    The session should not store such data as you said, the muzzle is from the server part in order to be separated so as not to load the server every time and do the monkey's work itself.

    BAD
    1. Start in the session the variable “Last access to registration”, where the timestamp on every step to register.
    2. Start in the session the variable "registration success", which assumes true if the registration is successful.
    3. When the registration script runs, you look at the difference in time stamps; if the difference exceeds for example 30 minutes, you clean the data of the old session, if you see the success of the registration, it is the same.

    BAD
    1. Every time you check something, pass a flag to the server with a gett or a post that this is a check.
    2. If there is no checkbox in the request, then it means that you need to clean the registration form data
    3. Better checkbox post

    IT IS PAST AND IT IS BAD, you can write a lot of such crutches here, and it won't be right.
    For good, too many options, I shared my experience.

      If it is a question of submitting data to the fields, if the user did not pass validation, then the simplest option is to return the results of the received data from the user via GET / POST and substitute the selected values ​​into your form. Session for this is not necessary. But it will work for simple forms. If you have a step-by-step form, you can move between steps, etc., this solution may not be suitable, depends on the implementation.

      Also, as an option, limit the lifetime of the session to a small value, within which we can assume that it is permissible to substitute previously filled values. For example, if more than 3 minutes have passed, the session dies. If during this time the user made the transitions, then we substitute the values.

      And another simple, but a crutch option is to process all incoming requests and check, if this is not the registration page, then kill the corresponding session. But the decision is, frankly, so-so.

        If you are impatient to store temporary data in a session, then I advise you to google FlashData - this mechanism is for one-time data acquisition. In many frameworks, this bun is available out of the box . If you use a self-written basis of the site, you will have to invent something similar.

          To save the value of the field it means to give out the value of this field, which was entered last time, and most importantly, after verification. If the user leaves the registration page and then returns, he does not expect to see the field values ​​there. But if he sends the form and receives an answer, he expects it.

          The simplest solution is to store the field values ​​"once", the answer was already higher.

          I will describe the idea of ​​implementation with a small example:

           <?php session_start(); ob_start(); $message = '<p>Так себе значение, я вам скажу</p>'; /* Ищем только в POST/GET */ $field = Param('field_name', false); if ($field !== NULL) { /* Есть какое-то значение поля */ if ($field == 'abc') { /* Хорошее значение - пишем об этом, проводим регистрацию, и переходим куда-нибудь */ $message = '<p>Бинго! Значение просто великолепно!</p>'; /* ... */ /* В случае успеха перенаправления нет, поэтому хорошее значение будет заморожено */ } else { /* В случае провала уничтожаем POST/GET перенаправлением на эту же страницу * Значения введенных полей будут взяты из сессии один раз, а POST-данные пропадут */ header("HTTP/1.0 302 Moved Temporarily", true, 302); header("Location: ".$_SERVER['REQUEST_URI'], true); exit(); } } else { /* Попытка поискать значение еще и в сессии */ $field = Param('field_name', true); } print '<html> <head> <title>797252</title> </head> <body> '.$message.' <p>Значение <code>abc</code> считается хорошим, все остальные нет</p> <form action="" method="post"> <input type="text" name="field_name" value="'.$field.'"> <input type="submit" value="Отправить форму"> </form> </body> </html> '; ob_flush(); /* Возвращает значение по имени из POST, если там нет, то из GET, а если и там нет, то при установленном флаге $use_cache ищет в SESSION['cache'] * Вернет NULL, если такого значения нигде нет */ function Param($field_name, $use_cache) { /* Не люблю Notice */ if (!isset($_SESSION['cache'])) { $_SESSION['cache'] = array(); } $value = NULL; if (isset($_POST[$field_name])) { /* Нашли в POST */ $value = $_POST[$field_name]; /* Кешируем */ $_SESSION['cache'][$field_name] = $value; } else if (isset($_GET[$field_name])) { /* Нашли в GET */ $value = $_GET[$field_name]; /* Кешируем */ $_SESSION['cache'][$field_name] = $value; } else if ($use_cache && isset($_SESSION['cache'][$field_name])) { /* Нашли в сессии */ $value = $_SESSION['cache'][$field_name]; /* Выбрасываем кеш, чтобы найти в сессии можно было только один раз */ unset($_SESSION['cache'][$field_name]); $_SESSION['cache'][$field_name] = NULL; } /* Вообще нигде не нашли */ return $value; } ?>