2

I need to take a variable that contains a URL, and check to see if the domain equals a certain domain, if it does, echo one variable, if not, echo another.

$domain = "http://www.google.com/docs";
if ($domain == google.com)
{ echo "yes"; }
else
{ echo "no"; }

Im not sure how to write the second line where it checks the domain to see if $domain contains the url in the if statement.

5 Answers 5

15

This is done by using parse_url:

$host = parse_url($domain, PHP_URL_HOST);
if($host == 'www.google.com') {
    // do something
}
2
  • You probably want more robust domain checking, as noted in Jonathan Sampson's answer. Commented Jul 13, 2009 at 23:11
  • 6
    How is a homemade regex more robust than a PHP built in? Commented Jul 14, 2009 at 3:46
7

Slightly more advanced domain-finding function.

$address = "http://www.google.com/apis/jquery";

if (get_domain($address) == "google.com") {
  print "Yes.";
}

function get_domain($url)
{
    $pieces = parse_url($url);
    $domain = isset($pieces['host']) ? $pieces['host'] : '';
    if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
        return $regs['domain'];
    }
    return false;
}
2

In addition to the other answers you could use a regex, like this one which looks for google.com in the domain name

$domain = "http://www.google.com/docs";
if (preg_match('{^http://[\w\.]*google.com/}i', $domain))
{

}
1
  • Yeah I didn't see what you were trying there. Commented Jul 13, 2009 at 21:55
1

Have you tried parse_url()?

Note that you might also want to explode() the resulting domain on '.', depending on exactly what you mean by 'domain'.

1

You can use the parse_url function to divide the URL into the separate parts (protocol/host/path/query string/etc). If you also want to allow www.google.com to be a synonym for google.com, you'll need to add an extra substring check (with substr) that makes sure that the latter part of the host matches the domain you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.