0

I am processing a HTML form with PHP. In case of an error (eg. too short string), I write back the string to the html input, to the value attribute. What is the recommended way?

The form input is:

<input type="text" name="firstname">

The PHP script is:

$variable_firstname = filter_input (INPUT_POST, 'firstname', FILTER_UNSAFE_RAW);
if ( mb_strlen($variable_firstname , 'UTF-8')  <  3 )
{
   print '<input type="text" name="firstname" value="'.$variable_firstname.'">';
}

Should I transform the string eg. with htmlspecialchars() before print?

Thanks!

DevinPHP
  • 37
  • 3
  • 2
    Yes, or you will be open to XSS attacks. The most common way today is using Ajax though. Then you don't leave the page at all and don't need to generate the form or the values again. It also results in a smoother user experience. – M. Eriksson Aug 04 '18 at 21:27
  • Yes. You may get further info in [this question](https://stackoverflow.com/questions/3126072/what-are-the-best-php-input-sanitizing-functions) – alariva Aug 04 '18 at 23:47

0 Answers0