Homepage detection

I like to detect Homepage using PHP code like:
if($_SERVER["REQUEST_URI"] != '/') {$level "is_front_page");}else {$level "is_home");}

Is this correct code or how to be improved?

I believe the line would be

if(strpos($_SERVER['REQUEST_URI'], '/') !== FALSE) { $level = "is_front_page"; }else{ $level = "is_home"; }

This however does cover domain.com/ or domain.com/index.php, both of which would be the home page as well.
If you have actual pages it would be easy to set a variable on the home page, $level = "is_home";

You might try this

$public_path = explode('/', $_SERVER['REQUEST_URI']);

if (count($public_path) < 2 || 
(count($public_path) == 2 && $public_path[1] == "index.php") || 
(count($public_path) == 2 && empty($public_path[1]))){ 
    $level = "is_home"; 
}else{
    $level = "is_front_page"; 
}

I think this would work or what you’re looking for?

$phpSelf = filter_input(INPUT_SERVER, 'PHP_SELF', FILTER_SANITIZE_URL);
$path_parts = pathinfo($phpSelf);
$basename = $path_parts['basename'];
if ($basename  == 'index.php') {
  echo "tada<br>\n";
}

Why go to all the trouble of setting $basename from $path_parts only to immediately override it with ‘index.php’?

This is a good example of one reason for always using === for comparison - that way when you accidentally leave one out it doesn’t break the code.

1 Like

Ooops good point…me bad :smile: I also accidently used = instead of ==then corrected it in the original post.

I don’t believe this will work if he uses a directory structure, e.g. /NewFolder/index.php

I prefer this method:

$level = (in_array( $_SERVER[“REQUEST_URI”], array( ‘/’, ‘/index.php’)) ? ‘is_home’ : ‘is_front_page’;
echo $level;

Yes, this (slightly modified) seems to work even for directories.

$level = (in_array( $_SERVER['REQUEST_URI'], array( '', '/', '/index.php')) ? 'is_home' : 'is_front_page');

Thank you for your replies.
I have an issue that there is Homepage also with /index.php but rest pages like en-gb/about-us/index.php

So, detection of / as ‘‘Rest pages’’ is not perfect solution. How to detect also this option?

It means language folder/category/index.php for rest pages and also needs detection of /. Detecton of / for rest pages will not work in this example as there is option inside URL like /index.php which already has / and it will detect / even there is Homepage.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.