PHP多页面表单刷新后数据丢失问题求助
Hey there! Let's sort out this issue where your form loses data when the page refreshes. The core problem here is that your current code relies on $_POST values, which only exist during the immediate form submission (a POST request). When you refresh the page, the browser sends a GET request instead—so those $_POST values vanish, and your input field goes back to empty.
To fix this, we'll use PHP sessions to persist the form data across page loads. Sessions store data server-side tied to the user's browser, so it stays around even when you refresh or navigate between pages. Here's how to adjust your code:
Updated Code
<?php // Start the session FIRST—this must go before any HTML output or echoes! session_start(); // When the form is submitted, save the name to the session if(isset($_POST['submit'])){ $_SESSION['name'] = $_POST['name']; } // Display the stored name if it exists if(isset($_SESSION['name'])){ echo $_SESSION['name'].'<br/>'; } ?> <form method="POST" action=""> <p>NAME</p> <input type="text" name="name" value="<?php echo isset($_SESSION['name']) ? htmlentities($_SESSION['name']) : ''; ?>" /> <br/> <input type="submit" value="keep value" name="submit"/> <br/> </form>
Key Notes:
session_start()is non-negotiable: It has to be the very first thing in your file, before any HTML tags, spaces, or echoes. If you put it after output, PHP will throw an error about headers already being sent.- Storing data in the session: When the user submits the form, we take the
$_POST['name']value and save it to$_SESSION['name']. This keeps the data stored server-side for the user's session. - Populating the input field: Now the input's
valuepulls from the session instead of just$_POST. Even if you refresh the page, the session still holds the value, so the input stays filled. - You’re already doing this right: Great job using
htmlentities()! It prevents cross-site scripting (XSS) attacks by escaping special characters—always keep that in mind when outputting user input.
For your multi-page form, this pattern scales perfectly: just start the session on every page, save each field's value to the session as the user submits each step, and populate form fields from the session. When the user finishes the last page, you can access all the stored data from $_SESSION to process it.
内容的提问来源于stack exchange,提问作者P.S.F.Romesh

