Below is the code.
I placed the code in the functions.php of the child theme in a WordPress installation.
As you can see I have it set to hook into the "init" function, feeling its the best place to run no matter what page a visitor goes to. Thats what my research have said. If there is someplace better please share.
Basically, the intended use is that the code should allow users coming from google.com host to access the site. If this is the case it also sets a cookie so that the user can access the other menu items without being redirected.
And if NOT coming initially from a google host, then it checks for the cookie and if no cookie it then redirects back to google.com (again google is just a placeholder, can't post actual host.)
The ISSUE is that:
if visitor goes to anyother page other than home, host variable is correct, but on the home page visit, the $host variable is blank or not set.
$host variable is always not set or blank. this is because the referring site uses Javscript to do some code and redirects before sending to my site. I can understand why it may not be "google.com but it should be set to something right?
This is where my lack of understanding of http_referrer comes in and I need assistance. I have read that checking for http_referrer has issues and it can be spoofed via code etc. I get it, my question is what can be done at this point to get SOMETHING in the $host variable, and why is it blank when just going to the home page of a WordPress site?
I require a way to deny access to the "lay person" who are not coming from the referral site. I dont need to stop hackers and coders, I just need to prevent people sharing the link via email or posting the site link on facebook and people just clicking the link.
function site_referral_check() {
if (!is_admin()){
$allowed_host = 'google.com'; // not actual production site
$theurl = $_SERVER['HTTP_REFERER'];
$host = parse_url($theurl, PHP_URL_HOST);
//add console variable for debugging. how I know when $host is blank
$javascript_ouput = "<script>console.log('Debug Info: " .$host. "');
</script>";
echo $javascript_ouput;
//echo "The allowed host: ".$allowed_host; exit;
if ( !isset($_COOKIE["site-referral"])) {
if ($host == $allowed_host) {
setcookie( "site-referral", "site-referral", time() + 1800, COOKIEPATH, COOKIE_DOMAIN);
}
if (!$host == $allowed_host) {
//Redirect
wp_redirect('http://google.com' ); exit;
}
}
}
}