I am currently using check_plain() etc on displaying user entered data in HTML, and I am also using check_plain() etc prior to inserting the user data into my custom tables.

When inserting or updating the DB, I am always using db_insert or db_merge. Do I need to validate like I am, or are those functions doing it for me already?

If they are doing that already, do I need to use check_plain() on output still?

1 Answer 1


I downvoted Devaraj Johnson's answer because it suggests to check_plain() data before saving it to the database, which is wrong.

The idea behind check_plain, filter_xss and filter_xss_admin is to prevent XSS attacks, which are related to the front end.

When you handle database queries, use parameters and the DB API to prevent SQL injection attacks. Whenever you output data to the browsers, use check_plain, and other security methods.

Note that check_plain(), filter_xss() and such functions do change the data. When you save data into the database, you are only escaping specific characters, but you do not alter the original text. If you use check_plain() in database insert/updates, saving data a few times can mess up your data with a lot of &, <, etc character replacements and some HTML tags stripped out.

Here are some good reads:

  • i just read drupal.org/writing-secure-code nice catch Feb 21, 2015 at 14:10
  • The general rule is to save the users input exactly, and then whenever you are outputting content added by a user to the page, use check_plain()
    – user44495
    Feb 21, 2015 at 14:56
  • @AyeshK Just a quick follow up - doing as suggested now, with check_plain on output. Do I need to do the same when I am using FAPI to edit that data e.g. #value => check_plain('previously entered user data')? Or is this only ever required when outputting as actual HTML?
    – Paul
    Mar 1, 2015 at 13:47
  • @AyeshK Urgh, sorry, I just re-read that second link and see that FAPI is a special case as it's already checked. Apologies for bothering you.
    – Paul
    Mar 1, 2015 at 13:50
  • 1
    No problemo. However, you do need to sanitize everything in #description, #prefix, #suffix, #markup` and such properties. #options also need sanitizing if you are using radios as #type.
    – AKS
    Mar 1, 2015 at 14:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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