Search code examples
phpescapinghtmlspecialcharsstrip-tags

How to properly escape tags in input text


looks like ordinary question but could not find correct solution. lets say I have this form:

<form name="form" action="nextpage.php">
<input type="text" name="input_name" value="<?php echo $_POST['input_name'];?>" />
<input type="submit" name="submit" value="Next"/>
</form>

For example if I add "My input text >" as value of the input the nextpage.php is broken. I tried to use for:value="<?php echo strip_tags($_POST['input_name']);?>" or :value="<?php echo htmlspecialchars($_POST['input_name']);?>" but none of them works.. Why is that and how to avoid it? Thanks


Solution

  • First, you should sanitize your posted value for security, but that aside, php provides a function that automatically escapes special characters called addslahes http://php.net/manual/en/function.addslashes.php, save your post value to a variable using the addslashes function, then use the variable as your value.