简体   繁体   中英

Retaining data in HTML form

I have an HTML form. Let's say I fill out all the fields and submit it (PHP script runs here). Then I want to go back to the form using "Back" button of my browser. What I see is the empty form. What do I do to have the entered data retain on the page after I come back to it using "Back" button of the browser?

Thank you!

如果使用浏览器的“后退”按钮,则浏览器负责重新填充表单数据。

Usually that functionality is handled by the browser, however if you want to "force" the fields to always be pre-filled with the user's data, you can store the $_POST data in a session variable and use that to load the form.

Example:

// submission page
session_start();
if(isset($_POST)){
  // save the posted data in the session
  $_SESSION["POST"] = $_POST;
}

Then on the actual form page, you can check to see if session data exists. It won't if the form is being loaded the first time, but it will if the user submits the form and then presses the browser back button:

// form page
session_start();
if(isset($_SESSION["POST"])){
  // previous POST data has been saved
  // build the form with pre-defined values from $_SESSION
  ...
} else {
  // no previous data
  // build the form without pre-defined values
  ...
}

Note that you must call session_start() before outputting any HTML.

Store the value in a session

session_start();

//form so that you have all the potential forms in a single session array
//form_1 to identify the form in question

if(!empty($_POST)){
$_SESSION['forms']['form_1'] = $_POST;//if this is for the public internet, then I would really consider making sure that the posted data matches the received data... (and that its comming from YOUR form), which is way too long to post here...
}

then on the form page

<input name="flowers" value="<?php echo if(isset($_SESSION['forms']['forms_1']['flowers'])){ echo htmlspecialchars($_SESSION['forms']['forms_1']['flowers']);} ?>" />

obviously the above can be simplified, but for a example's sake it's better this way.

(make sure to clean out the old form data eventually)

You can potentially store the data in the session, and re-populate it back using PHP sessions. You should create a separate back button that takes you to the previous page.

Example:

Storing data:

$_SESSION['data'] = $_POST['item1'];

In the HTML Forms:

<input type="text" name="someinput" value="<?=$_SESSION['data']?>" />

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