Function and usage of esc_url_raw() in wordpress

Question

Answers ( 1 )

    0
    2024-01-06T02:29:36+00:00

    The esc_url_raw() function in WordPress is designed for sanitizing URLs before they are used in a database or for redirection purposes. This function acts as an alias for sanitize_url(), which means it performs the same operations as sanitize_url().

    Here's a detailed breakdown of esc_url_raw():

    Function:

    esc_url_raw( string $url, string[] $protocols = null ): string
    

    Description:

    • The esc_url_raw() function is primarily used to clean URLs to ensure they are safe to use in the database or for redirects. This is crucial to prevent security vulnerabilities such as cross-site scripting (XSS) attacks.
    • As an alias of sanitize_url(), it performs similar sanitization processes.

    Parameters:

    1. $url (string, required):

      • This is the URL that you want to sanitize.
      • Example: 'https://www.example.com?param=value'
    2. $protocols (string[], optional):

      • An array of acceptable protocols that the URL may use.
      • If not specified, this defaults to the return value of wp_allowed_protocols(), which usually includes common protocols like http, https, mailto, etc.
      • Example: ['http', 'https', 'mailto']

    Return:

    • Type: string
    • Description: The function returns the sanitized version of the input URL. If the URL is deemed unsafe or uses an unacceptable protocol, the function may return an empty string or a modified version of the URL that removes the problematic parts.

    Sample Usage:

    Here’s an example of how you might use esc_url_raw() in a WordPress plugin or theme:

    $url = 'https://www.example.com/some-page?param=value';
    $protocols = ['http', 'https'];
    
    // Sanitize the URL
    $safe_url = esc_url_raw($url, $protocols);
    
    // Use the sanitized URL for database insertion or redirection
    // For example, inserting into the database:
    $wpdb->insert('your_table_name', array('url_column' => $safe_url));
    

    In this example, $url is the URL to be sanitized, and $protocols is an optional array of acceptable protocols. The sanitized URL, $safe_url, is then safe to be used for further processing, such as database storage or redirects.

    Additional Notes:

    • It’s important to use functions like esc_url_raw() when dealing with URLs submitted by users or derived from untrusted sources.
    • Remember that while esc_url_raw() sanitizes URLs for safe use, it does not escape them for HTML output. Use esc_url() if you need to echo a sanitized URL in an HTML attribute.

Leave an answer