Skip to content
PHP Logo

What is the difference between accessing a URL with "www." and without it, and why is it important in PHP?

When accessing a URL with "www.", it can be considered as a subdomain of the main domain without "www.". This difference can affect how cookies are handled, session data is stored, and how URLs are processed in PHP. To ensure consistency and avoid potential issues, it is important to redirect all requests to either include or exclude "www." in the URL.

php
// Redirect all requests to include or exclude "www." in the URL
if (strpos($_SERVER['HTTP_HOST'], 'www.') === 0) {
    header('Location: http://' . substr($_SERVER['HTTP_HOST'], 4) . $_SERVER['REQUEST_URI']);
    exit();
}