Are there any best practices for handling external domain links in PHP functions like url2link?

When handling external domain links in PHP functions like url2link, it is important to validate the URLs before processing them to prevent security vulnerabilities such as XSS attacks. One way to do this is by using PHP's filter_var() function with the FILTER_VALIDATE_URL filter to ensure that the URL is valid. Additionally, you can use functions like parse_url() to extract the domain from the URL and compare it against a whitelist of allowed domains.

function url2link($url) {
    $allowed_domains = array('example.com', 'google.com', 'facebook.com');
    
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        $parsed_url = parse_url($url);
        $domain = $parsed_url['host'];
        
        if (in_array($domain, $allowed_domains)) {
            return '<a href="' . $url . '">' . $url . '</a>';
        } else {
            return 'External links are not allowed.';
        }
    } else {
        return 'Invalid URL.';
    }
}