php – How to keep the user saved in the<form> still misspelling the password?

Question:

Suppose we have a form, and its validations written with PHP. The variables are collected with POST, there are two fields (username and password), and a submit button.

Well, the user enters her credentials and accidentally miswrites the password. I would like the user's name, at least, to be recorded in the <input> so that I don't have to type it again.

Answer:

If you want the form to show the same username when the username / password verification is incorrect, you can use the following code:

<?php
if (empty($_POST['usuario']) === false) {
  /* Hacer comprobaciones de entrada */
}
/* Si la entrada fue infructuosa muestras el formulario como de costumbre */
?><form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
  <input
    type="text" name="usuario"
    value="<?= isset($_POST['usuario'])?htmlspecialchars($_POST['usuario']):'' ?>"
  />
</form>

As you can see, in case the form had been previously submitted, the value field will be filled with its value making use of htmlspecialchars() to convert special characters into HTML entities (such as quotation marks " that would close the value field prematurely) .

Scroll to Top