1

My gut tells me wrapping esc_attr() in intval() is redundant when it comes to escaping input, but I would like to double-check.

Also: considering that <option value="">- select no. -</option> is hardcoded/value is null, that chunk of input wouldn't need to be escaped, correct?

Here is my current code set-up:

        <select name="_number">
        <option value="">- select no. -</option>
            <?php
            $savedNo = intval( get_post_meta( $post->ID, '_number', true ) );
            for ($x = 1; $x <= 100; $x++) {
                echo '<option value="'
                    . intval(esc_attr($x)) . '"'
                    . ($x === $savedNo ? ' selected="selected"' : '' )
                    . '>'
                    . 'No. ' . intval(esc_attr($x))
                . '</option>';
            }
            ?>
        </select>

Thank you!

2

Based on WordPress documentation for esc_attr function, it is returning a string value. So, If you need to have the integer value, you need using intval function. But, when you want to display that value or put it as part of markup, it doesn't make sense.

Escape functions are useful for outputting and printing values. If you want to save a value in the database, the data type is a matter and you may need to use intval function alongside sanitization.

-1

In your case you don't need any of these functions on $x, because its values are created by for loop and are safe.

  • Why would a loop make it safe? – kaiser Jan 23 at 20:07
  • @kaiser What is possible scenario in OP example how $x value may get compromised? It is not user input, it is assigned by loop itself and used only in loop scope. Maybe I am wrong, but I really want to understand how in this case it can be anything else than integer? – Vitauts Stočka Jan 23 at 20:29
  • Open your dev-tools, change the value of an option and you got user generated input. – kaiser Jan 23 at 21:43
  • @kaiser Sure, and it MUST be escaped or otherwise considered unsafe when you are processing POST request from user. But have you seen OP example? $x value there is not received from user input and could not be changed, no matter what he/she does in dev-tools or other way. Escaping in THIS case is just unnecessary operation. – Vitauts Stočka Jan 24 at 5:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.