quakeglen
quakeglen

Reputation: 165

How to check if url is homepage with parameters in php and mod_rewrite

I need to write a function to check if the URL is homepage, even if user uses parameters. Apache's mod_rewrite is enabled to support pretty urls.

I just came across with this function, but after trying on facebook links its returns false when should be true.

function isHomePage(){
    if(trim($_SERVER['REQUEST_URI'])=='/'){
        return true;
    }
}

Current results:

/ = true
/?id=someid = false
/page/ = false
/page/?id=someid = false

Expected results:

/ = true
/?id=someid = true
/page/ = false
/page/?id=someid = false

Upvotes: 0

Views: 761

Answers (1)

KIKO Software
KIKO Software

Reputation: 16688

There are two problem you need to solve, if your software itself doesn't know where it is (which is weird):

  1. Get the URL path without anything else.
  2. Determine if it is the home page.

Number one can be done in various ways, but the best one, I think is to use parse_url() on the $_SERVER['REQUEST_URI'], the URI which was given in order to access a page.

Number two depends completely on which URLs you send to the home page. There are usually multiple URLs for this, so you should check them all.

This would give this code:

function isHomePage()
{
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    return in_array($path, ['/', '/home.html', '/index']);
}

Clearly you would have to change the array, with homepage URLs, to suit your needs.

Upvotes: 2

Related Questions