user317005
user317005

Reputation:

How do I write a function that tells me that I am currently looking at the homepage (/index.php)?

PHP:

function is_homepage()
{
}

if(is_homepage())
{
    echo 'You are on the homepage';
}
else
{
    echo 'You are not on the homepage';
}

Explanation:

is_homepage, should work in all these cases:

Where it shouldn't work:

Upvotes: 2

Views: 95

Answers (3)

Tudor Constantin
Tudor Constantin

Reputation: 26861

function is_homepage()
{
  return ( ( $_SERVER['HTTP_HOST'] == 'www.domain.com' || $_SERVER['HTTP_HOST'] == 'domain.com') && substr( $_SERVER['REQUEST_URI'], 0, 9 ) == 'index.php' );

}

if(is_homepage())
{
    echo 'You are on the homepage';
}
else
{
    echo 'You are not on the homepage';
}

Upvotes: 0

Gajus
Gajus

Reputation: 73828

It depends of course on how your PHP script is laid out. Though the following solution would work in most cases:

$_SERVER['SCRIPT_NAME'] == '/index.php'

Upvotes: 4

Oliver M Grech
Oliver M Grech

Reputation: 3171

do a

print_r($_SERVER);

and you'll see all the data which will help you achieve this.

I would use

$_SERVER['PHP_SELF']

to identify the file\page I'm currently working with.

Upvotes: 6

Related Questions