How to Sanitize User Input in PHP?

It’s a question almost every PHP developer asks yourself. By me the most simple way to sanitize the user input is to save everything in the database with no loosing of tags or whatever HTML markup and than on displaying this on the client side to strip_tags if needed.

In example when saving a HTML formatted text you can use simply the htmlspecialchars method

$description = htmlspecialchars($_POST['description']);

Than you can be sure everything’s in the database, but it’s not actually HTML. Thus you don’t have any tags at all in the database field.

When you show this in the client side and you’d like to strip some tags, i.e. to keep only the <a> tag you can do this:

echo strip_tags(htmlspecialchars_decode($description), '<a>');

That’s the most simple way to keep everything as the original source. By me it’s better to keep whatever HTML markup there is on the input.

3 thoughts on “How to Sanitize User Input in PHP?

  1. I much prefer htmlentities over htmlspecialchars. Also, you titled this wrong, because other than converting a few tags, this does not sanatize your data much. As @seanJA pointed out, you are still open to SQL injection attacts too.

    This is by no means anything that I would use to sanatize user input.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>