wppaste
WordPress

esc_url( string $url, string[] $protocols = null, string $_context = 'display' ): string

Since
2.8.0, 6.9.0
Source
wp-includes/formatting.php:4480

Clean a URL for safe output with esc_url(): it strips invalid characters, rejects disallowed protocols, and encodes ampersands for display. A URL using a protocol outside the allowed list (or an empty URL) comes back as an empty string, so a javascript: payload never reaches the page.

Checks and cleans a URL.

Description

A number of characters are removed from the URL. If the URL is for displaying (the default behavior) ampersands are also replaced. The 'clean_url' filter is applied to the returned cleaned URL.

Compatibility

WordPress
since 6.9.0
PHP
7.4–8.6-dev
  • 6.7.7
  • 6.8.8
  • 6.9.7
  • 7.0.4
  • 7.1.0

Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.

Parameters

$urlstring
The URL to be cleaned.
$protocolsstring[]optional
An array of acceptable protocols.
Defaults to return value of wp_allowed_protocols().Default: null
$_contextstringoptional
Private. Use sanitize_url() for database usage.Default: 'display'

Return value

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.

Code examples

Every example is editable and runs in a real WordPress booted in your browser by WordPress Playground. Press Run, then edit the code: clicking away re-runs it. Nothing is sent anywhere until you do.

Output a link stored in post meta

esc_url() strips characters that would break out of the attribute and drops protocols that are not allowed.

update_post_meta( 2, 'author_website', 'https://example.com/profile?id=7&ref="x' );

$website = get_post_meta( 2, 'author_website', true );

echo "raw:     ", $website, "\n";
echo "escaped: ", esc_url( $website ), "\n\n";
echo 'javascript: URL becomes: ', var_export( esc_url( 'javascript:alert(1)' ), true );

Use esc_url_raw() when storing or passing a URL to an HTTP call, not esc_url().

Allow only https URLs

Pass the $protocols array to restrict which schemes are acceptable; anything else returns an empty string you can treat as invalid.

$promo_video = get_theme_mod( 'promo_video_url', '' );
$safe_src    = esc_url( $promo_video, array( 'https' ) );

if ( '' !== $safe_src ) {
	echo '<iframe class="promo-video" src="' . $safe_src . '" loading="lazy"></iframe>';
}

By default the allowed protocols come from wp_allowed_protocols(), which includes mailto:, tel:, ftp:, and others; pass an explicit array when you want links narrower than that.

Performance profile

How much work a call to esc_url() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.

Cost class
Trivial

Touches nothing outside its own arguments.

Scaling
Constant

No loop in the body: the same number of instructions runs whatever you pass in.

Instructions
46–113

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 146.

Plugin surface
1 hook

Third-party callbacks on 'clean_url' run inside this call, and their cost is not bounded by anything here.

Called by
50

50 places in core call this, so the cost is paid more often than your own code shows.

What it touches

  • hookthird-party callbacksapply_filters()called directly

What one call costs · 20 distinct outcomes

One number would be a lie: the work depends on which branch runs. These are every distinct cost esc_url() can have, taken from its control-flow graph on PHP 8.5.

WhenInstructionsCalls it makes
$url !== "" && $_context !== "display" && !$url46–49ltrim(), stripos(), apply_filters()
$url !== "" && $_context !== "display" && !$url && is_array($protocols)53–56ltrim(), stripos(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $_context === "display"56ltrim(), stripos(), wp_kses_normalize_entities(), apply_filters()
$url !== "" && $_context !== "display" && !$url && !is_array($protocols)56–59ltrim(), stripos(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $_context !== "display" && !$url && is_array($protocols)59–62ltrim(), stripos(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $_context !== "display" && !$url && !is_array($protocols)62–65ltrim(), stripos(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $_context === "display" && is_array($protocols)63ltrim(), stripos(), wp_kses_normalize_entities(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $_context === "display" && !is_array($protocols)66ltrim(), stripos(), wp_kses_normalize_entities(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $_context === "display" && is_array($protocols)69ltrim(), stripos(), wp_kses_normalize_entities(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $url && $_context !== "display"72–89ltrim(), stripos(), wp_parse_url(), apply_filters()
$url !== "" && $_context === "display" && !is_array($protocols)72ltrim(), stripos(), wp_kses_normalize_entities(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $url && $_context !== "display" && is_array($protocols)79–96ltrim(), stripos(), wp_parse_url(), wp_kses_bad_protocol(), strtolower(), strtolower()
8 further outcomes, up to 113 instructions
$url !== "" && $url && $_context === "display"82–97ltrim(), stripos(), wp_kses_normalize_entities(), wp_parse_url(), apply_filters()
$url !== "" && $url && $_context !== "display" && !is_array($protocols)82–99ltrim(), stripos(), wp_parse_url(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $url && $_context !== "display" && is_array($protocols)85–102ltrim(), stripos(), wp_parse_url(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $url && $_context !== "display" && !is_array($protocols)88–105ltrim(), stripos(), wp_parse_url(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $url && $_context === "display" && is_array($protocols)89–104ltrim(), stripos(), wp_kses_normalize_entities(), wp_parse_url(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $url && $_context === "display" && !is_array($protocols)92–107ltrim(), stripos(), wp_kses_normalize_entities(), wp_parse_url(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower()
$url !== "" && $url && $_context === "display" && is_array($protocols)95–110ltrim(), stripos(), wp_kses_normalize_entities(), wp_parse_url(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()
$url !== "" && $url && $_context === "display" && !is_array($protocols)98–113ltrim(), stripos(), wp_kses_normalize_entities(), wp_parse_url(), wp_allowed_protocols(), wp_kses_bad_protocol(), strtolower(), strtolower(), apply_filters()

This body has more branch combinations than are worth enumerating, so the table covers the outcomes found first rather than every one that exists.

Across PHP versions

PHPCompiledExecutedBranchesNotes
8.6-dev14646–11322
8.514646–11322
8.414646–1132238 fewer instructions than PHP 8.3
8.318464–14822
8.218464–14822
8.118464–14822
7.418464–14822

An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.

Hooks and filters fired · 1

One hook fires while esc_url() runs, in this order:

  1. apply_filters( clean_url )filterline 4578 (+98 into the body)

    Filters a string cleaned and escaped for output as a URL.

Uses · 9

Used by · 50

Show all 50

Source code

function esc_url( $url, $protocols = null, $_context = 'display' ) {	$original_url = $url; 	if ( '' === $url ) {		return $url;	} 	$url = str_replace( ' ', '%20', ltrim( $url ) );	$url = preg_replace( '|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url ); 	if ( '' === $url ) {		return $url;	} 	if ( 0 !== stripos( $url, 'mailto:' ) ) {		$strip = array( '%0d', '%0a', '%0D', '%0A' );		$url   = _deep_replace( $strip, $url );	} 	$url = str_replace( ';//', '://', $url );	/*	 * If the URL doesn't appear to contain a scheme, we presume	 * it needs http:// prepended (unless it's a relative link	 * starting with /, # or ?, or a PHP file). If the first item	 * in $protocols is 'https', then https:// is prepended.	 */	if ( ! str_contains( $url, ':' ) && ! in_array( $url[0], array( '/', '#', '?' ), true ) &&		! preg_match( '/^[a-z0-9-]+?\.php/i', $url )	) {		$scheme = ( is_array( $protocols ) && 'https' === array_first( $protocols ) ) ? 'https://' : 'http://';		$url    = $scheme . $url;	} 	// Replace ampersands and single quotes only when displaying.	if ( 'display' === $_context ) {		$url = wp_kses_normalize_entities( $url );		$url = str_replace( '&amp;', '&#038;', $url );		$url = str_replace( "'", '&#039;', $url );	} 	if ( str_contains( $url, '[' ) || str_contains( $url, ']' ) ) { 		$parsed = wp_parse_url( $url );		$front  = ''; 		if ( isset( $parsed['scheme'] ) ) {			$front .= $parsed['scheme'] . '://';		} elseif ( '/' === $url[0] ) {			$front .= '//';		} 		if ( isset( $parsed['user'] ) ) {			$front .= $parsed['user'];		} 		if ( isset( $parsed['pass'] ) ) {			$front .= ':' . $parsed['pass'];		} 		if ( isset( $parsed['user'] ) || isset( $parsed['pass'] ) ) {			$front .= '@';		} 		if ( isset( $parsed['host'] ) ) {			$front .= $parsed['host'];		} 		if ( isset( $parsed['port'] ) ) {			$front .= ':' . $parsed['port'];		} 		$end_dirty = str_replace( $front, '', $url );		$end_clean = str_replace( array( '[', ']' ), array( '%5B', '%5D' ), $end_dirty );		$url       = str_replace( $end_dirty, $end_clean, $url ); 	} 	if ( '/' === $url[0] ) {		$good_protocol_url = $url;	} else {

Changelog

Introduced in 2.8.0. Unchanged from 6.7.7 through 7.1.0.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 7.1.0

Signature, return type and hooks compared across 5 parsed releases.

6.9.0
Prepends https:// to the URL if it does not already contain a scheme and the first item in $protocols is 'https'.from the docblock
2.8.0
Introduced.from the docblock

About this page

Parsed data
Generated from the wordpress-develop 7.0.4 tag, from src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it.
Corrections
Something wrong on this page? Report it and it gets fixed in the next regeneration.