How can PHP be used to retain user input values in form fields upon page reload?

When a form is submitted and the page reloads, PHP can be used to retain user input values in form fields by checking if the form has been submitted and storing the values in variables. These variables can then be echoed into the form fields as the default values. By doing this, users don't have to re-enter all their information if there are errors in the form submission.

<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Store user input values in variables
    $username = $_POST['username'];
    $email = $_POST['email'];
} else {
    // Set default values if form has not been submitted
    $username = "";
    $email = "";
}
?>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
    <input type="text" name="username" value="<?php echo $username; ?>" placeholder="Username">
    <input type="email" name="email" value="<?php echo $email; ?>" placeholder="Email">
    <button type="submit">Submit</button>
</form>