• Resolved Guido

    (@guido07111975)


    Hi dear forum users,

    Within my plugin I output a HTML string if value “hook” is true.

    
    if(hook == true) {
      $before = '<div class="hook">';
      $after = '</div>';
    } else {
      $before = esc_attr('');
      $after = esc_attr('');
    }
    echo $before . $some-value . $after;
    

    I know, this is not best coding practice, but I just wondering whether or not it’s necessary to escape the empty variable in this case? Because this value is always empty if “hook” is false. So the variable does not contain anything which can be used as hook by malicious scripts.

    Guido

Viewing 6 replies - 1 through 6 (of 6 total)
  • No, you’re right, it’s not necessary.

    You should use escaping functions when you can’t trust the value. This would include any user input (even from admin accounts), external content (such as from an API), values from another script or template, or even translations.

    For translations, when you use __( 'My text' ) a translation file can replace that content. To reduce the risk of malicious translation files doing something nasty you should escape translatable text. WordPress provides functions like esc_html__() and esc_html_e() as escaped versions of __() and _e().

    But if you’re setting the values in the code yourself, you don’t need to escape them.

    Marcus Kober

    (@marcuskober)

    Hi there,

    no, that’s not necessary. But you have a problem in your code: if you want to output the variable, please use double quotes (“) instead. With single quotes echo will output just the dollar sign and the variable name:

    $before = '';
    $after = '';
    if ($hook == true) {
      $before = '<div class="hook">';
      $after = '</div>';
    }
    echo "$before $some_value $after";

    And please don’t forget the dollar sign in the if clause (you are using hook instead of $hook and keep in mind that variable names couldn’t include dashes, but underscores ($some_value instead of $some-value)…

    Marcus Kober

    (@marcuskober)

    Oh, you’ve corrected the echo in the meantime. ??

    Thread Starter Guido

    (@guido07111975)

    Hi Jacob and Marcus,

    Thanks for the quick response.

    You should use escaping functions when you can’t trust the value.

    That’s the explanation I needed; my value is always empty in that case, so it can be trusted. No escaping needed ??

    Oh, you’ve corrected the echo in the meantime.

    Yup, I noticed myself it wasn’t correct ??

    @ritart12 what do you mean?

    Guido

    Moderator Jan Dembowski

    (@jdembowski)

    Forum Moderator and Brute Squad

    Hi Guido, that user ritart12 was a spammer and is now blocked.

    Thread Starter Guido

    (@guido07111975)

    Thanks, I already thought his link was looking suspicious..

    Guido

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘Escaping this empty variable necessary?’ is closed to new replies.