简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM