Are there any best practices for handling URLs with or without "www" in PHP scripts?

When handling URLs in PHP scripts, it is best practice to normalize URLs to either include or exclude the "www" prefix for consistency and to avoid duplicate content issues. One way to achieve this is by using the PHP `parse_url()` function to extract the hostname from the URL, then checking if it starts with "www." If it does, remove the "www" prefix. This ensures that all URLs within the script are uniform.

$url = "http://www.example.com/page";
$parsed_url = parse_url($url);

if (substr($parsed_url['host'], 0, 4) === 'www.') {
    $parsed_url['host'] = substr($parsed_url['host'], 4);
    $normalized_url = $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'];
} else {
    $normalized_url = $url;
}

echo $normalized_url;