Question

I'm experimenting with creating a commenting system. I'm using php-OEmbed class and HTML Purifier. What filter can I use to ensure that the comments are safe to be inserted into my database? I know you can use PHP filters such as FILTER_SANITIZE_STRING, but won't these turn the HTML into entities?

Also if you use something like the WMD editor, do you then have to use something on the client side as well (like PHP Markdown) to ensure that it is safe?

Was it helpful?

Solution

Basically you need to sanitize user input whenever you send it somewhere.

When you put it into your database you need to prevent SQL injection by quoting SQL special characters (prepared statements will do this for you). When you send it to a browser you need to escape HTML special characters (PHP has functions for doing this) to prevent script injection.

There may be other places where you need to escape special characters, too. For example, if you send the comments to a Bash script on the server to do some kind of processing. In that case you'd need to quote or escape Bash-specific special characters.

It's important to not quote/escape at the wrong stage: for example, don't escape HTML entities when you put it into the database unless you are absolutely sure of what you're doing. It's very easy to accidentally escape things again when you pull it out of the database and prepare to send it to a browser, or not escape things at all if you are sending an error message if the database connection fails (this could cause an XSS vulnerability). Do your escaping at the last moment and you will most likely avoid these pitfalls.

OTHER TIPS

You don't need to use any filter for SQL injection. A preferable solution is to use prepared statements. For instance, PDO provides PDOStatement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top