Remove www. from $_SERVER['HTTP_HOST']

Discussion in 'PHP' started by nick-a, Nov 19, 2007.

  1. #1
    Anyone got a routine to remove the www. from the server http_host variable?

    Cheeres,
    Nick
     
    nick-a, Nov 19, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    $host = str_replace('www.', null, $_SERVER['HTTP_HOST']);
    
    PHP:
     
    nico_swd, Nov 19, 2007 IP
    nick-a likes this.
  3. kemus

    kemus Guest

    Messages:
    487
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    0
    #3
    
    function strstr_after($haystack, $needle, $case_insensitive = false) {
        $strpos = ($case_insensitive) ? 'stripos' : 'strpos';
        $pos = $strpos($haystack, $needle);
        if (is_int($pos)) {
            return substr($haystack, $pos + strlen($needle));
        }
        // Most likely false or null
        return $pos;
    }
    $domain=strstr_after("$_SERVER['HTTP_HOST']","www.",TRUE);
    print $domain;
    
    PHP:
     
    kemus, Nov 19, 2007 IP
  4. nick-a

    nick-a Active Member

    Messages:
    446
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    58
    #4
    Thanks nico that's brilliant, didn't think of it that way, I just wrote

    $host = substr($domain, 4, 40); and it worked, but not as clean as your version which I'll use,

    Cheers,
    Nick
     
    nick-a, Nov 19, 2007 IP
  5. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #5
    This would throw a parse error.
     
    nico_swd, Nov 19, 2007 IP
  6. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #6
    Note that the www. depends on the domain in the URL. If someone visits your site without the www., you'd remove the first characters from your actual domain name.
     
    nico_swd, Nov 19, 2007 IP
  7. nick-a

    nick-a Active Member

    Messages:
    446
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    58
    #7
    The code I used worked fine..but I'm using yours now. I wrapped it in a ereg www if else etc to figure out when to do what.

    Cheers,
    Nick
     
    nick-a, Nov 19, 2007 IP
  8. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #8
    Usually, there is not more than one occurrence of "www.", so if you use the str_replace(), it'll remove the www., or it'll leave the string like it is, if there's no www.. So you don't need to overkill it with checking and verifying. You can just use str_replace() and it'll give you always the same result.
     
    nico_swd, Nov 19, 2007 IP