sanitize_url()
Cleans the specified URL so that it can be safely used for redirects or stored in the database.
See also: wp_sanitize_redirect().
Uses: esc_url()
Used By: get_url_in_content()
1 time — 0.0000241 sec (very fast) | 50000 times — 0.12 sec (very fast) | PHP 7.4.33, WP 6.2
No Hooks.
Returns
String. Cleaned URL (processed by the esc_url() function with the context 'db').
Usage
sanitize_url( $url, $protocols );
- $url(string) (required)
- URL that needs to be cleaned.
- $protocols(string[])
- Array of accepted protocols. See the wp_allowed_protocols() function.
Default: return value of wp_allowed_protocols()
Examples
#1 Example of work
var_dump( sanitize_url('www.example.com') ); // http://www.example.com
var_dump( sanitize_url('example.com') ); // http://example.com
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" #2 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 );
#3 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/
#4 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 );
Notes
- See: esc_url()
Changelog
| Since 2.3.1 | Introduced. |
| Since 2.8.0 | Deprecated in favor of esc_url_raw(). |
| Since 5.9.0 | Restored (un-deprecated). |
| Since 6.9.0 | Prepends https:// to the URL if it does not already contain a scheme and the first item in $protocols is 'https'. |
sanitize_url() sanitize url code WP 6.9.1
function sanitize_url( $url, $protocols = null ) {
return esc_url( $url, $protocols, 'db' );
}