Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if URL entered is from a certain domain

Tags:

php

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 }
  • http://www.google.com/blah - works
  • https://www.google.com/blah - works
  • google.com/blah - doesn't work
  • www.google.com/blah - doesn't work

Is there a way to do this without regex? If not, how would it be done?

Thanks.

like image 982
Burrows Avatar asked Sep 09 '13 16:09

Burrows


People also ask

How can I tell if a URL is used?

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.

How do I find the domain of a URL?

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.

How do you check if the URL contains a given string in PHP?

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).


1 Answers

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!

like image 157
Amal Murali Avatar answered Oct 11 '22 19:10

Amal Murali