bikey77
bikey77

Reputation: 6672

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.

Upvotes: 2

Views: 9363

Answers (5)

pavitran
pavitran

Reputation: 814

This would work:

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

Upvotes: 0

user2511140
user2511140

Reputation: 1688

Use this

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

Upvotes: 1

site stats
site stats

Reputation: 264

$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!

Upvotes: 0

DaveRandom
DaveRandom

Reputation: 88647

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';

N.B. 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.

Upvotes: 5

Egor Sazanovich
Egor Sazanovich

Reputation: 5089

$url = parse_url($_SERVER['HTTP_REFERER']);
$url = explode('/',$url['path']);
if ($url[1]=='index.html'||empty($url[1])) echo 'from index ';

Upvotes: 0

Related Questions