简体   繁体   中英

How to keep form values even after page is redirected back

This is not a simple "after post" situation, because, page is getting redirected back here.

I have a little bit large form with about 20 or more input fields.

So, the user fills the form and submits, and after server-side validation (if there's an error), the user is redirected back to the same page with the form. But no values. So, he has to fill this whole thing up every time just because one wrong input.

So, how to get over this problem...

I have seen some people suggesting to use $_SESSION to hold these data. Is it safe ? I have more than 20 inputs and that's kind of a large amount of data..

If you are not using a certain PHP Framework, there are several ways of doing this.

1) Yes, you can use $_SESSION to store the information if you encounter a certain invalid field after submission. Remember to use session_start() in order to start/access the session. This is a safe method, unless you are worrying about session hijacking; but that's a different topic, with its own prevention methods.

2) You can have your form submit to the same page as your form's HTML (or the page/function requiring the HTML form itself). You can check at the beginning if $_POST is not empty or is set. If so, you can perform your field checking things and insert into the database. If you encounter an invalid field then you can continue to (or require) the form HTML. You will still have access to $_POST and you can therefore fill the form fields again. Your code can have

<input type="text" name="first_name" value="<?php if(isset($_POST['first_name'])) echo $_POST['first_name'];?>" />

I believe this is the proper way to handle your issue because it is a much optimal way than going into the hassle of using the $_SESSION in this way. I don't believe you need to actually "store" data for your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM