PHP Form Complete

PHP Form Complete: Retaining User Data

We have covered form handling, data cleaning, required fields, and format validation. Now it is time to put it all together!

There is one final user-experience (UX) feature to add: Retaining form values. If a user submits a form and makes a mistake (like entering an invalid email), they shouldn't have to re-type all their other valid data!


Keeping Values in the Inputs

To show the values in the input fields after the user hits the submit button, we add a little PHP script directly inside the value attribute of the HTML input fields:

Name: <input type="text" name="name" value="<?php echo $name; ?>">
E-mail: <input type="text" name="email" value="<?php echo $email; ?>">

Now, whatever data the PHP script saved into the $name and $email variables will be echoed right back into the input boxes.


The Complete Script

Here is how the complete backend logic looks when combining everything we've learned over the last four lessons:

Complete Validation Example

<?php
// 1. Initialize variables
$name = $email = "";
$nameErr = $emailErr = "";

// 2. Custom Security Function function test_input($data) { $data = trim($data); $data = stripslashes($data); return htmlspecialchars($data); }

// Simulate form submission with an invalid email $_SERVER["REQUEST_METHOD"] = "POST"; $_POST["name"] = "Alice"; $_POST["email"] = "alice@badformat";

// 3. Processing the Form if ($_SERVER["REQUEST_METHOD"] == "POST") {

// Name Validation if (empty($_POST["name"])) { $nameErr = "Name is required."; } else { $name = test_input($_POST["name"]); }

// Email Validation if (empty($_POST["email"])) { $emailErr = "Email is required."; } else { $email = test_input($_POST["email"]);

// Check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
  $emailErr = "Invalid email format!"; 
}

}

echo "Saved Name: " . $name . "<br>"; echo "Email Error: " . $emailErr; } ?>

You have now successfully mastered secure form handling in PHP!


Exercise

?

How can you keep a user's typed value visible inside a text input field after they submit a form?