简体   繁体   中英

PHP check if referral url is the homepage

I'm trying to figure out how to check if the referral url to one of my inner pages is the homepage. This would be easy if the homepage was always www.mysite.com/index.php but what happens when it's simply www.mysite.com?

I know I could simply do

$url = $_SERVER['HTTP_REFERER'];
$pos = strrpos($url, "/");
$page = substr($url, $pos+1, (strlen($url)-$pos+1));
if (substr_count($url, 'index')) echo 'from index ';

but I don't have the index.php in my $url variable.

parse_url() can help you here.

// An array of paths that we consider to be the home page
$homePagePaths = array (
  '/index.php',
  '/'
);

$parts = parse_url($_SERVER['HTTP_REFERER']);
if (empty($parts['path']) || in_array($parts['path'], $homePagePaths)) echo 'from index';

NB This should not be relied upon for anything important. The Referer: header may be missing from the request, and can easily be spoofed. All major browsers should do what you expect them to, but hackers and webcrawlers may not.

Use this

if($_SERVER["REQUEST_URI"] == "/" || $_SERVER["REQUEST_URI"] == "/index.php")
   echo "Home";

这将工作:

if ($_SERVER['REQUEST_URI'] == '/')

$url = parse_url($_SERVER['HTTP_REFERER']);
$url = explode('/',$url['path']);
if ($url[1]=='index.html'||empty($url[1])) echo 'from index ';
$referer = $_SERVER['HTTP_REFERER'];
$homepage = "index.php";
$ref_array = explode("/", $referer);
if(trim($ref_array[1]) == trim($homepage) || trim($ref_array[1]) == "") echo "From URL";

You should note that yoursite.com/index.php and yoursite.com/ is the same!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM