How to recover data from an invalid form? PHP

0

I have a registration form that I send to a php script that does the processing and writes to bd, the problem is that when some field of the form is invalid, I redirect to the form, but it goes blank, I thought write the fields in $_SESSION , but it seems to be a bit tricky like that.
Any suggestions?

    
asked by anonymous 14.02.2017 / 14:50

2 answers

1

If you are using $_POST or $_GET to send the data, when you validate the data, it identifies that it is invalid and displays the form again, the data is still available to you.

So depending on how your form may change a little, but the idea is to do something like this:

<input type="text" value="<?=isset($_POST['nome'])?$_POST['nome']:''?>" name="nome">

According to your comments, the form is in a different request than the data processing. Then the $_SESSION is an alternative. It would not look much different from $_POST , just put everything in an aray to avoid some possible conflict

In validation:

$_SESSION['form_foo'] = $_POST;

No form:

<input type="text" value="<?=isset($_SESSION['form_foo']['nome'])?$_SESSION['form_foo']['nome']:''?>" name="nome">
    
14.02.2017 / 15:03
1

If the request is handled in the same file, Marcos's response , where it is used directly variable $_POST , is valid. If it is necessary to treat the request in different files, I believe that session is not the best output, but cookie . Although they seem to be the same, the purpose is different. HTTP requests are characterized as stateless , because data does not persist between multiple requests, as soon as the response to the request is obtained the data is lost. The goal of session and cookie is to persist for a while some data that is interesting to the application in question, the difference is that session persists the data on the server side and cookies side of the user. Since we are working with a form, in which the user will provide the data itself, there is no risk to the application persisting the data on the user side . For the server, it only matters the data when they are already valid.

A discussion of this can be read here:

In this way, your form can be defined following the same logic presented in the other response, but now replacing the variable $_POST with $_COOKIE :

<input type="text" value="<?= isset($_COOKIE['form_foo']['nome']) ? $_COOKIE['form_foo']['nome'] : '' ?>" name="nome">

And in the file that handles the requests, after validating the data, persist them through the function setcookie .

    
14.02.2017 / 19:08