PHP switch with GET request

后端 未结 6 2000
南旧
南旧 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:36

    Use $_SERVER['QUERY_STRING'] – that contains the bits after the ?:

    switch($_SERVER['QUERY_STRING']) {
        case 'home':
            echo 'admin home';
            break;
    }
    

    You can take this method even further and have URLs like this:

    http://mysite.com/admin/?users/user/16/
    

    Just use explode() to split the query string into segments, get the first one and pass the rest as arguments for the method:

    $args = explode('/', rtrim($_SERVER['QUERY_STRING'], '/'));
    $method = array_shift($args);
    
    switch($method) {
        case 'users':
            $user_id = $args[2];
    
            doSomething($user_id);
            break;
    }
    

    This method is popular in many frameworks that employ the MVC pattern. An additional step to get rid of the ? altogether is to use mod_rewrite on Apache servers, but I think that's a bit out of scope for this question.

提交回复
热议问题