Check if URL is from a certain website

后端 未结 2 1669
情书的邮戳
情书的邮戳 2021-01-29 11:52

Problem

The user can submit a form where he can submit a link to sitea.com. Now what I want to do is check if the user actually submitted an URL coming fr

2条回答
  •  悲哀的现实
    2021-01-29 12:32

    I think it's best parse_url() here. Regex may work, but it's best to avoid using regex when a built-in function is available.

    I'd do something like:

    $url = '...';
    $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
    
    if ($domain == 'sitea.com') {
        # code...
    }
    

    As a function:

    function getDomain($url) 
    {
        $domain = implode('.', array_slice(explode('.', parse_url($url, PHP_URL_HOST)), -2));
        if ($domain == 'sitea.com') {
            return True;
        } else {
            return False;
        }
    
    }
    

    Test cases:

    var_dump(getDomain('http://sitea.com/'));
    var_dump(getDomain('http://sitea.com/directory'));
    var_dump(getDomain('http://subdomain.sitea.com/'));
    var_dump(getDomain('http://sub.subdomain.sitea.com/#test'));
    
    var_dump(getDomain('http://subdomain.notsitea.com/#dsdf'));
    var_dump(getDomain('http://sitea.somesite.com'));
    var_dump(getDomain('http://example.com/sitea.com'));
    var_dump(getDomain('http://sitea.example.com/test.php?haha=sitea.com'));
    

    Output:

    bool(true)
    bool(true)
    bool(true)
    bool(true)
    
    bool(false)
    bool(false)
    bool(false)
    bool(false)
    

    Demo!

提交回复
热议问题