I'm really confused on this.



What is the best way to sanitize variable?

$var_one = get_option( ‘variable_one’ );
echo esc_html( $var_one );


$var_one = esc_attr( get_option( ‘variable_one’ ) );
echo esc_html( $var_one );

does the code #2 doubles the sanitization?

thank you!


There is 2 major rules when dealing with sanitizing:

1 - Sanitize have to follow the current scope so if you want print something on attribute use esc_attr() if you want print the same thing as HTML use esc_html() or printf()

2 - Always sanitize just right before the output that’s mean:
instead of :

$x = esc_html($string);
echo $x;


$x = $string;
echo esc_html($x);


Thanks. What about if we use the variables like this

$x = $string;
if( esc_html( $string ) ) { content }


$x = $string;
$args = array(
‘post_type’ => esc_html( $string )

are those accepted?


Have you tried the code you just write ?! You can’t use esc_html inside if condition because it will always return the string

You need to escape TWO things user input and user output, However escaping is not just about protecting your software from malware or bad people it’s more than that it’s about keeping your software running with random inputs and bad server configuration.

So if you want use if condition to check your string you need more than that, Here you are an example:

if ( !empty( $x ) AND strpos( $x, ‘<’ ) == false ) { }

The code inside the condition will be executed if your string wasn’t empty and doesn’t have any HTML tag.

WARNING: Do not use the above code in a production product.