开发者

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

开发者 https://www.devze.com 2023-03-07 13:36 出处:网络
PHP: function is_homepage() { } if(is_homepage()) { echo \'You are on the homepage\'; } else { echo \'You are not on the homepage\';

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:

  • http://www.domain.com
  • https://www.domain.com
  • http://domain.com
  • http://domain.com/?param=value
  • http://domain.com/index.php?param=value

Where it shouldn't work:


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.


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'


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

精彩评论

暂无评论...
验证码 换一张
取 消