Why would you use esc_attr() on internal functions?

I see a lot of these in premium themes/plugins.

#1 - Why would you escape this? It's your own data. For consistency?

function prefix_a() {
    $class_attr = 'a b c';

    // Some more code.

    return 'div class=' . esc_attr( $class_attr ) . 'Content/div';
}

// Called somewhere.
prefix_a();

#2 - Again, why? The data doesn't come from the DB.

function prefix_b( $class ) {
    // Some code.

    return 'div class=' . esc_attr( $class ) . 'Content/div';
}

// Called by a developer from the team.
prefix_b( 'developer adds a class' );

Yes, a child theme developer might call the function above, but he/she is already in control.

#3 - Why? If someone can add filters, it can do a lot more.

function prefix_c() {
    $class_attr = apply_filters( 'prefix_c', 'foo bar' );

    // Some code.

    return 'div class=' . esc_attr( $class_attr ) . 'Content/div';
}

// Called somewhere.
prefix_c();

I can only think about consistency and to be safe if someone uses untrusted data (excluding the #1 case).

Topic escaping plugin-development security theme-development Wordpress

Category Web


  1. You probably wouldn't. If you did it would be to make sure it was in place already if in future you decided to make the variable dynamic or filterable.
  2. In this case I would suggest it for similar reasons to #1. You may know where $class is coming from now, but this may change in future, and it prepares the function for potential use in different contexts where $class may not be controlled.
  3. You need to escape here because you know for certain that your code has no control over what the value of $class may be, and you should make sure that your code does not break if an improper value is passed. This is not solely a security concern. As you will learn from following questions on this site, many developers who use filters do not necessarily know what they are doing. They may write code that takes a dynamic value and adds it as a class using your filter. Most of the time this might be fine, but what if they are automatically pulling something in like a post title? Eventually there may be a post title with a " character, and this will break the markup of their site if you do not escape the values from that filter. An experienced developer would know what the problem is and escape it themselves, but not all developers who might use your filter are quite as experienced.

I think the best answer is in the official doc: https://developer.wordpress.org/plugins/security/securing-output/

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.