Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm confused about the different uses of esc_html() and wp_kses(). I understand that esc_html() converts special characters to their HTML entity, and that wp_kses() removes unwanted tags (e.g., <script>), but I'm not sure in what contexts they should be used together or separately.

If I run some untrusted HTML through esc_html(), then any JavaScript will be displayed in plain text rather than being rendered by the browser, so it is safe at that point, correct? The only reason to also run it through wp_kses() would be to avoid having the raw script displayed?

Basically, esc_html() makes it safe, and wp_kses() makes it pretty. Is that correct?

share|improve this question
add comment

2 Answers

up vote 7 down vote accepted

The general rule, at least as espoused by Mark Jaquith, is sanitize on input, escape on output (the corollary to this rule being sanitize early, escape late).

So: use sanitization filters (such as the kses() family) when storing untrusted data in the database, and use escaping filters (i.e. the esc_*() family) when outputting untrusted data in the template.

share|improve this answer
    
Ah, ok, that makes more sense now. Thanks :) –  Ian Dunn Oct 14 '11 at 21:03
add comment

The kses functions should be used when you want to allow some subset of html to be in the result. For example, comments allow some HTML in them for bold, italic, links, and such.

The esc_html function should be used to escape html completely. No HTML will go through it without being converted to something that will be interpreted as non-HTML by a browser.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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