Home > Mobile >  Is PHP data escaping essential in conditions too?
Is PHP data escaping essential in conditions too?

Time:12-22

I work on WordPress and would like to know if you should escape data only when actually displaying the data on screen, like:

<h2><?php echo esc_html($customer_name); ?></h2>

or should you also escape in condition such as:

<input type="text" name="customer_name" id="customer_name"
  <?php echo ( esc_html( $customer_name ) && !empty( esc_html( $customer_name )) ? 'value="'.esc_attr( $customer_name ).'"' : '' ) ; ?>>

Thank you.

CodePudding user response:

Generally speaking, no, you do not need to do escaping in that scenario, only when outputting.

There is a theoretical edge-case scenario where the escaping changes the text in some fashion that affects your condition. For instance, if you want to test if escaping (for whatever reason) introduced an HTML entity such as  . However, for that scenario you aren't testing the variable, you are testing the escaping function and it should be obvious, hopefully.

For functions that render something such as selected(), you'll want to think about whether they echo what you give them. In that function's case only a comparison is done, so no escaping is needed (nor is it probably correct). If the function does echo something, that's when I'd recommend either going to the docs, or checking the function's source to determine if it is needed.

This was initially a series of comments but was unified into a single answer.

  • Related