I have a field where a user can enter a URL. I need to check if that URL is from a certain domain, in this case google.com
.
I've tried this, however, it doesn't work for all cases (which I list below):
if(strstr(parse_url($link, PHP_URL_HOST), 'google.com') { // continue }
Is there a way to do this without regex? If not, how would it be done?
Thanks.
With checkdomain you can check a URL and then receive the information whether the desired URL is still free. If a URL has been checked and it is occupied, you will also receive information about who bought this domain. If a URL is free, you can register it directly in your name via our website.
Simply put, a domain name (or just 'domain') is the name of a website. It's what comes after “@” in an email address, or after “www.” in a web address. If someone asks how to find you online, what you tell them is usually your domain name.
Method 1: strpos() Function: The strpos() function is used to find the first occurrence of a sub string in a string. If sub string exists then the function returns the starting index of the sub string else returns False if the sub string is not found in the string (URL).
parse_url
requires a valid URL and google.com/blah
isn't valid (as of PHP 5.3.3) -- so it won't work. As a work around, you can append the http
if doesn't exist already, and then check the domain.
Use the following function:
function checkRootDomain($url)
{
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
$domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
if ($domain == 'google.com') {
return True;
} else {
return False;
}
}
Test cases:
var_dump(checkRootDomain('http://www.google.com/blah'));
var_dump(checkRootDomain('https://www.google.com/blah '));
var_dump(checkRootDomain('google.com/blah'));
var_dump(checkRootDomain('www.google.com/blah '));
Result:
bool(true)
bool(true)
bool(true)
bool(true)
It is a modified version of my own answer here.
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With