In a lot of how to create a custom meta box tutorials, when saving data, i.e., update_post_meta the data is escaped:
update_post_meta( $post_id, 'city', esc_attr( ucwords( $_POST['city'] ) ) );
Some tutorials do not esc when saving and do it on screen output.
However, escaping protects the output to the screen, i.e., echo:
echo esc_attr( $city );
So does it matter if you esc before you output to the screen or before it’s saved?
If you esc on save does the order of esc-ing, sanitizing and validating matter?
Do you esc then sanitize and validate or sanitize, esc and sanitize . . . etc.?
Yes it does. Escaping depends on context and in worst case like using esc_html
when writing directly to the DB are just a security hole.
Even if there is no security issue, there is theoretical one. The user asked you to store A, and you are storing B. In a simple cases B is exactly how A should be displayed in the HTML, but life is rarely simple and while at one point you want to display A in an input for which you want to do esc_attr
and at another in a textarea for which you will want to use esc_html
. If you already transformed A into B in the DB, it is a PITA to reconstruct for B what was the original A to apply the correct escape function on it.
Rule of thumb: In the DB you should store the raw values the user submitted (probably sanitized, but not escaped), escaping should be done only on output.