0

If I have a front-end post form where a user enters a url, is it OK and recommended to use esc_url() twice - once for cleaning the input before using update_post_meta for database storage, and again on output.

// escape url before using update_post_meta
update_post_meta( $post_id, 'url', esc_url( $url ) );

// escape url on output
echo esc_url( get_post_meta( $post_id, 'url', true ) );

Any help appreciated.

4

It's okay to use it more than once, but not encouraged. However, in your first example, you're saving the URL to the database. When you do that, or when using the URL in the wp_remote_* context, or a redirect, or any other non-display context, you should be using esc_url_raw() instead.

Also note that get_post_meta will return an array, unless the third argument $single is set to true. If you're dealing with a single key-value pair you'll want:

echo esc_url( get_post_meta( $post_id, 'url', true ) );

Hope that helps!

  • Yeah that makes sense, just looked at the esc_url_raw function and it uses esc_url but with the third parameter 'db', perfect for storing it in the database with update_post_meta. And yes, I forgot to add the true parameter at the end of the get_post_meta. – Andy Nov 22 '16 at 15:07
1

According to the Wordpress codex, it appears it would be better to pass the first URL using esc_url_raw

The esc_url_raw() function is similar to esc_url() (and actually uses it), but unlike esc_url() it does not replace entities for display. The resulting URL is safe to use in database queries, redirects and HTTP requests.

So, it should probably be written like this:

// escape url before using update_post_meta
update_post_meta( $post_id, 'url', esc_url_raw( $url ) );

// escape url on output
echo esc_url( get_post_meta( $post_id, 'url', true ) );

So, to recap, esc_url_raw for database storage, and esc_url for display.

1

I just want to mention the possibility of validating the user input before storing it and then escape it when you display it.

There's e.g. the filter_var() PHP function with the FILTER_VALIDATE_URL flag.

There's also the wp_http_validate_url() function, that's applied for the wp_safe_remote_{post,request,get} calls, to avoid redirection and request forgery attacks, as mentioned in the inline docs.

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.