13

It seems that they do almost same type of job. So...

When should I use esc_html() instead of sanitize_text_field()?

1 Answer 1

21

esc_html() is more or less lossless — it just turns HTML markup into encoded visible text, so that it's not rendered as markup by browser.

Semantically it's escape, so it's meant to be used to make output to page safe.

sanitize_text_field() however actually removes all HTML markup, as well as extra whitespace. It leaves nothing but plain text.

Semantically it's sanitize, so it's meant to be used to make input being saved safe.

5
  • isn't it better to use esc_html for both output and saving? I won't display any markup anyway.. so when would i use sanitize_text_field() ?
    – yeahman
    Apr 20, 2014 at 14:15
  • 1
    @yeahman "better" how? They are doing distinctly different things. Discarding markup usually used for things where markup isn't expected, for example form that takes a name.
    – Rarst
    Apr 20, 2014 at 14:37
  • I mean it stores what the user sees and has input... like you said it's lossless..(e.g. he inputs "the tag <head> is where you should include your css files", he expects to see the <head> in his post). For a name field, i would control the input via validation; isn't it more suited?
    – yeahman
    Apr 20, 2014 at 15:40
  • I'm interested in the differences between sanitize_text_field() and strip_tags
    – myol
    Jan 29, 2015 at 14:24
  • strip_tags is used in sanitize_text_field() if I am not wrong
    – yeahman
    Feb 23, 2016 at 19:47

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.