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.
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 );
Choice between
esc_url
andesc_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.:esc_url_raw
should be used for any other use, where the url should be treated as a valid url, e.g. redirect:or HTTP API functions:
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 useesc_url
the&
is converted in&
not when you useesc_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 useesc_url_raw
when you set the meta:Then when you retrieve it, use
esc_url_raw
oresc_url
according to your needs: if you have to print in the html useesc_url
otherwise useesc_url_raw
.