sanitize_url()WP 2.3.1

Sanitizes a URL for database or redirect usage.

Uses: esc_url()
1 time — 0.0000241 sec (very fast) | 50000 times — 0.12 sec (very fast) | PHP 7.4.33, WP 6.2

No Hooks.

Return

String. The cleaned URL after esc_url() is run with the 'db' context.

Usage

sanitize_url( $url, $protocols );
$url(string) (required)
The URL to be cleaned.
$protocols(string[])
An array of acceptable protocols.
Default: return value of wp_allowed_protocols()

Examples

0

#1 Clearing URLs for use in header()

A simplified code snippet of the rest_output_link_header() function:

$url = get_rest_url();

header( sprintf( 'Link: <%s>; rel="https://api.w.org/"', sanitize_url( $url ) ), false );

/////////////////////

$url= rest_url( rest_get_queried_resource_route() );

header( sprintf( 'Link: <%s>; rel="alternate"; type="application/json"', sanitize_url( $url ) ), false );
0

#2 Skip only http/https links

With sanitize_url() you can not only clean the url, but also filter by protocol:

// Link to ftp resource
$url     = 'ftp://ftp.cdrom.com/pub/music/songs/1996';
$new_url = sanitize_url( $url, [ 'http', 'https' ] ); //> empty (string)

// The usual link to the https site
$url     = 'https://site.example/projects/';
$new_url = sanitize_url( $url, [ 'http', 'https' ] ); //> https://site.example/projects/
0

#3 Cleaning url before saving

Snippet from the code of the edit_user() function:

$user = new stdClass();

if ( isset( $_POST['url'] ) ) {
	$user->user_url = sanitize_url( $_POST['url'] );
}

$user_id = wp_insert_user( $user );
0

#4 Example of work

var_dump( sanitize_url('https://example.com/foo') );       // https://example.com/foo
var_dump( sanitize_url('https://example.com/foo-%2F-M') ); // https://example.com/foo-%2F-M
var_dump( sanitize_url('/foo') );                          // /foo

var_dump( sanitize_url('') ); // string(0) ""
var_dump( sanitize_url(false) ); // string(0) ""
var_dump( sanitize_url(null) ); // string(0) ""
var_dump( sanitize_url(true) ); // string(8) "http://1"

Notes

Changelog

Since 2.3.1 Introduced.
Since 2.8.0 Deprecated in favor of esc_url_raw().
Since 5.9.0 Restored (un-deprecated).

sanitize_url() code WP 6.5.2

function sanitize_url( $url, $protocols = null ) {
	return esc_url( $url, $protocols, 'db' );
}