You should add some checks, for example:
function hasSubdomain($url) {
$parsed = parse_url($url);
$exploded = explode('.', $parsed["host"]);
if(count($exploded) > 2){
return true;
}else{
return false;
}
}
if(!hasSubdomain($_SERVER['SERVER_NAME'])){
$_SERVER['SERVER_NAME']="sub.example.com";
}