Search code examples
phphtmlformssecurityhtml-manipulation

Refill form after submit without able to manipulate the code


Normally I'm using a code like this for forms. The PHP code in it is to refill the form, e.g. if something is missing or so:

<form action="" method="post">
    <input type="text" name="first_name" <?php if (isset($_POST['first_name'])) { echo "value=\"".$_POST['first_name']."\"";} ?>><br>
    <input type="text" name="last_name" <?php if (isset($_POST['last_name'])) { echo "value=\"".$_POST['last_name']."\"";} ?>><br>
    <input type="submit" name="submit">
</form>

A security tool just told me a hacker could manipulate my code if filling e.g. "><p>Hello!!!</p> and then submit. Could a hacker also manipulate PHP code or only HTML?

Is this a big secure issue?

What's the best way to prevent this? Is it enough to just search an remove special characters like > and "? Or is there a better, more elegant way?


Solution

  • Yes it is a serious issue. It is an XSS attack. An attacker can inject a malicious script this way. https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)

    In order to avoid this kind of attacks, you should escape HTML tags. Here is a PHP library that does it: http://php.net/manual/en/function.htmlspecialchars.php