1

Is there a way to sanitize database input (say, for a comment form), which also allows for the end user to use basic HTML styling markup? As in, if a user wraps their text in <i>/<em> or <strong>/<bold>, the text gets styled, all while preventing users from entering malicious PHP and SQL commands?

  • First you have to decide what tags you will allow. Then you can strip all others (including <?php). To prevent SQL injection, use prepared statements (the details depend on what DB abstraction layer do you use). – dezso Oct 31 '12 at 14:50
4

There have been a few great discussions of this at Stack Overflow. This one covers methods and processes, but don't try to create a catch-all function as a replacement for understanding your data flows.

For your particular problem, it looks like HTML Purifier might be a good fit. That way, you could whitelist very specific HTML functionality (e.g., strong, ol, em) to prevent XSS. In addition, you can parameterize your queries (check out Bobby Tables for PHP specifics) to prevent SQL injection.

I wouldn't think of these two as one process, though, because they're really useful at different points in your application lifecycle: parameterizing your SQL queries is important when you're about to make a SQL call, but XSS protection is important when displaying the saved data in a Javascript-equipped browser (as opposed to saving text to the database).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.