I’m confused about URL sanitization in meta boxes

I’m making a meta box for a custom post and this meta box will contain a href value. I don’t need any validation as this is a valid href value but I would like to do this in a way that’s secure.

I have built my meta box with this tutorial.

Read More

In the part where to sanitize the input I have used esc_url_raw() and it seems to work just fine, but the Codex says on esc_url_raw():

This function is not safe to use for displaying the URL, use
esc_url() instead

So should I use esc_url() or is there something else that I should be using and if so, why should I not use esc_url_raw() in this case?

My Code:

/* Get the posted data and sanitize it */
$new_meta_value = ( isset( $_POST['mod-modbox-link'] ) ? esc_url_raw( $_POST['mod-modbox-link'] ) : '' );

I get the URLs to pages with this:

$my_link = get_post_meta( $post->ID, 'mod_modbox_link', true );

Related posts

1 comment

  1. Choice between esc_url and esc_url_raw depends on the use you have to do with the url.

    If you have to use the url to display inside html use esc_url, E.g.:

    $my_link = get_post_meta( $post->ID, 'mod_modbox_link', true );
    echo '<a href="' . esc_url($my_link) . '">Open link</a>'
    

    esc_url_raw should be used for any other use, where the url should be treated as a valid url, e.g. redirect:

    $my_link = get_post_meta( $post->ID, 'mod_modbox_link', true );
    wp_redirect( esc_url_raw($my_link) );
    

    or HTTP API functions:

    $my_link = get_post_meta( $post->ID, 'mod_modbox_link', true );
    $response = wp_remote_get( esc_url_raw($my_link) );
    

    This is because esc_url converts special htmlentities in their encoded versions, esc_url_raw doesn’t.
    E.g. if your url is something like http://example.com/index.php?foo=bar&bar=baz that is a full valid url, when you use esc_url the & is converted in &#038 not when you use esc_url_raw.

    Codex say to use esc_url_raw also to save url in db, and in your case the post meta is saved in database, so you should use esc_url_raw when you set the meta:

    $link = isset($_POST['meta']) ? esc_url_raw($_POST['meta']) : '';
    update_post_meta( $post_id, 'mod_modbox_link', $link );
    

    Then when you retrieve it, use esc_url_raw or esc_url according to your needs: if you have to print in the html use esc_url otherwise use esc_url_raw.

Comments are closed.