Search code examples
phphtmlspecialchars

php htmlspecialchars() from one form to another


Why can't htmlspecialchars() continually encode characters after each form submission? Take a look at the following example:

<?php $_POST['txt'] = htmlspecialchars($_POST['txt']); ?>
<form method="post">
<input name="txt" value="<?=$_POST['txt'] ?>" />
<input type="submit" name="save" value="test" />
</form>

You can see it at running at http://verticalcms.com/htmlspecialchars.php.

Now do the following

1) Type & into the text field
2) Hit the test button once
3) When the page completes post back, hit the test button again
4) When the page completes post back, view the page source code

In the input box, the value is & amp;

I was expecting & amp; amp;

Why is it not & amp; amp; ???


Solution

  • This simply is HTML entity encoding. When using "&" in an HTML attribute, it should be encoded. And this is what you are doing.

    So, the browser reads

    <input value="&amp;" />
    

    and translates it to an "textbox widget with value '&'".

    The same would be true for other special chars:

    <input value="&quot" />
    

    would result in a " character.

    When you submit the form, the browser sends these values unencoded, therefore your PHP script receives it like "&", not "&amp;".