PHP switch with GET request

后端 未结 6 2016
南旧
南旧 2021-02-03 16:12

I am building a simple admin area for my site and I want the URLs to look somewhat like this:

http://mysite.com/admin/?home
http://mysite.com/admin/?settings
htt         


        
6条回答
  •  逝去的感伤
    2021-02-03 16:41

    You can make your links "look nicer" by using the $_SERVER['REQUEST_URI'] variable.

    This would allow you to use URLs like:

    http://mysite.com/admin/home
    http://mysite.com/admin/settings
    http://mysite.com/admin/users
    

    The PHP code used:

    // get the script name (index.php)
    $doc_self = trim(end(explode('/', __FILE__)));
    
    /*
     * explode the uri segments from the url i.e.: 
     * http://mysite.com/admin/home 
     * yields:
     * $uri_segs[0] = admin
     * $uri_segs[1] = home
     */ 
    
    // this also lower cases the segments just incase the user puts /ADMIN/Users or something crazy
    $uri_segs = array_values(array_filter(explode('/', strtolower($_SERVER["REQUEST_URI"]))));
    if($uri_segs[0] === (String)$doc_self)
    {
        // remove script from uri (index.php)
        unset($uri_segs[0]);
    }
    $uri_segs = array_values($uri_segs);
    
    // $uri_segs[1] would give the segment after /admin/
    switch ($uri_segs[1]) {
        case 'settings':
            $page_name = 'settings';
            break;
        case 'users':
            $page_name = 'users';
            break;
        // use 'home' if selected or if an unexpected value is given
        case 'home':
        default: 
            $page_name = 'home';
            break;
    }
    

提交回复
热议问题