how does esc_html__
(the 2nd one) protect the $message
variable from being hacked ? what’s the point to use this protection here (the second one with a plain text)?
<?php
function unknown(){
/* If the user input any text, escape it. */
if ( !empty ( $_POST['unknown'] ) )
$message = esc_html ( $_POST['unknown'] );
/* If no text was input, use a default, translated message. */
else
$message = esc_html__( 'No message input by the user.', 'unknown' );
return $message;
}
?>
Thanks
It really doesn’t do much in that scenario. If you’re going to leave that message as a string constant instead of something that is system or user generated, you’re fine using one of the other translation functions:
__()
or_x()
.esc_html__()
is a little overkill for that particular line of code.Edit:
The main reason for the
esc_
functions is to protect your site against bad input, either intentional or accidental. You’re going to want to use the appropriate function whenever you’re working with any data that can be manipulated by a user or is not explicitly set by you.If you have any questions about WP functions in the future my recommendation would be to check the source. Either do a search in a WP install to find the function, or click the link at the bottom of the codex page that links to the source file.
One major principle of preventing security holes is “Escape late.” That means that, ideally,
esc_html()
oresc_attr()
should be used right when you echo or return the final HTML, not before. So, that’s one thing that the example you gave gets wrong.As for the purpose of
esc_html__()
, as I understand it, is to prevent weird characters from translated strings (not the original ones you see in the code) from messing up textareas and such.