Using WordPress ‘esc_url_raw()’ PHP function

The esc_url_raw() WordPress PHP function sanitizes a URL for database or redirect usage. It essentially cleans up the URL to ensure it doesn’t contain any harmful or unexpected characters. This function is an alias for sanitize_url().

Usage

Here’s a basic usage example for this function:

$url = 'http://example.com';
$response = wp_remote_get( esc_url_raw( $url ) );
if ( ! is_wp_error( $response ) ) {
  echo wp_remote_retrieve_body( $response );
}

In this example, esc_url_raw() is used to sanitize the URL before it’s passed to wp_remote_get().

Parameters

  • $url (string – required): The URL to be cleaned.
  • $protocols (string – optional): An array of acceptable protocols. Defaults to the return value of wp_allowed_protocols().

More information

See WordPress Developer Resources: esc_url_raw()

It’s important to note that esc_url_raw() should not be used to escape HTML entities in URLs. For that purpose, use esc_url() instead.

Examples

Basic Usage

Sanitizing a URL for a remote GET request.

$url = 'http://example.com';
$response = wp_remote_get( esc_url_raw( $url ) );
if ( ! is_wp_error( $response ) ) {
  echo wp_remote_retrieve_body( $response );
}

Sanitizing a URL for Database Storage

Cleaning a URL before storing it in the database.

$url = 'http://example.com?param=value';
$safe_url = esc_url_raw( $url );
update_option( 'my_option', $safe_url );

With Custom Protocols

Sanitizing a URL with a custom set of protocols.

$url = 'ftp://example.com';
$safe_url = esc_url_raw( $url, array( 'http', 'https', 'ftp' ) );

In a Redirect

Cleaning a URL before using it in a redirect.

$url = $_GET['redirect_to'];
wp_redirect( esc_url_raw( $url ) );
exit;

In an HTTP API Request

Sanitizing a URL before passing it to the HTTP API.

$url = 'http://example.com';
$response = wp_remote_post( esc_url_raw( $url ), $args );