Skip to content
PHP Logo

How can PHP developers handle the inconsistency in $_SERVER['SERVER_NAME'] returning the domain with or without www?

When using $_SERVER['SERVER_NAME'] in PHP, developers may encounter inconsistency where the domain is returned with or without the www prefix. To handle this, developers can check if the domain starts with 'www.' and remove it if necessary to ensure consistency in their application.

php
$serverName = $_SERVER['SERVER_NAME'];
if (substr($serverName, 0, 4) === 'www.') {
    $serverName = substr($serverName, 4);
}
echo $serverName;