esc_url()
Cleans the URL for use in text, changes the wrong and removes the dangerous characters.
esc_url() unlike esc_url_raw() prepares a string for displaying.
Always use esc_url() when you need to clean URLs, for example, for text or HTML attributes.
The function creates characters in the form of HTML entities, use it when creating (X)HTML or XML documents. For example, it changes the ampersand &
and quotation mark '
for their HTML entities &
, '
.
Avoid URLs without protocol. Every URL must begin with http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed or telnet
Hooks from the function
Return
String
. The cleaned URL after the clean_url filter is applied. An empty string is returned if $url specifies a protocol other than those in $protocols, or if $url contains an empty string.
Usage
esc_url( $url, $protocols, $_context );
- $url(string) (required)
- The URL to be cleaned.
- $protocols(array)
- An array of acceptable protocols. By default: http, https, ftp, ftps, mailto, news, irc, gopher, nntp, feed, telnet.
Default: null - $_context(string)
How the URL will be used. May be:
display
- ampersand ( & ) and quotes (') will be replaced with HTML entities.db
- standard sanitize.''
- standard sanitize.
Default: 'display'
Examples
#1 Basic Example
$url = "http;//example.com/link?var='some&"; echo esc_url( $url ); //> http://example.com/link?var='some& $url = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAD///////neHiwAAAAF3RST/+8RwZ=='; echo esc_url( $url ); //> '' echo esc_url( '#some' ); //> #some var_dump( esc_url( '' ) ); // string(0) "" var_dump( esc_url( false ) ); // string(0) "" var_dump( esc_url( null ) ); // string(0) ""
#2 Relative URL
echo esc_url( '/foo' ); //> /foo
#3 Comparison with urlencode()
-
urlencode()
- encodes the passed string so that it can be used as part of the URL (without the domain). If you pass the whole URL, it becomes unusable. esc_url()
- handles the whole URL (does not break it), takes care of the safe display of the URL - it removes or changes some characters in the URL (not like urlencode() does).
$url = "http://example.com/моя ссылка?var='some&"; echo esc_url( $url ); // http://example.com/моя%20ссылка?var='some& echo urlencode( $url ); // http%3A%2F%2Fexample.com%2F%D0%BC%D0%BE%D1%8F+%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B0%3Fvar%3D%27some%26
Changelog
Since 2.8.0 | Introduced. |