How do I only allow visitors from a certain domain see a page on my website?

Discussion in 'PHP' started by sebastya, Feb 13, 2014.

  1. #1
    sebastya, Feb 13, 2014 IP
  2. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #2
    On the example.com/page-7, add to the top:
    
    $domain = false;
    if (isset($_SERVER['HTTP_REFERER'])) {
         $domain = parse_url($_SERVER['HTTP_REFERER'],  PHP_URL_HOST);  
    }
    if ($domain != 'referral.com' && $domain != 'www.referral.com') {
        die('Invalid redirect');
    }
    
    PHP:
    However, you have to keep in mind that the HTTP_REFERER can easily be faked via headers. A good way, if you own both domains, is to redirect with a custom header that contains a token known to both sides. It won't make it fool proof, but would deter most of scrapers. A fool proof way would be to use shared db to store the sessions when links are clicked via a proxy page on your site: ex: referral.com/proxy.php which adds a custom token to the db and passed it via a GET param to your site, which your site checks the DB and then deletes it.
     
    ThePHPMaster, Feb 13, 2014 IP
  3. livedating

    livedating Active Member

    Messages:
    161
    Likes Received:
    0
    Best Answers:
    1
    Trophy Points:
    83
    #3
    Here is a shorter version if you prefer this style of coding:
    if (! in_array(parse_url(@$_SERVER['HTTP_REFERER'], PHP_URL_HOST), ['referral.com', 'www.referral.com'])) die("Not allowed");
    PHP:
    (requires PHP 5.4)
     
    livedating, Feb 14, 2014 IP