PHP switch with GET request

I am creating a simple administration area for my site and I want the URLs to look something like this:

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

But I'm not sure how to get information about which page is being requested, and then display the desired page. I tried this on my switch:

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

But I get this error:

Fatal error: Cannot use [] for reading in C:\path\to\web\directory\admin\index.php on line 40

Is there any way around this? I want to not set a value for the GET request, for example:

http://mysite.com/admin/?action=home

If you know what I mean. Thank you. :)

+3
source share
6 answers

Use $_SERVER['QUERY_STRING']- which contains bits after ?:

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

You can use this method even more and have the following URLs:

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

explode(), , :

$args = explode('/', rtrim($_SERVER['QUERY_STRING'], '/'));
$method = array_shift($args);

switch($method) {
    case 'users':
        $user_id = $args[2];

        doSomething($user_id);
        break;
}

, MVC. , ? , mod_rewrite Apache, , .

+11

, key($_GET), $_GET, , URL-

www.example.com/?home&myvar = 1;

, reset() , key .

+2

$_SERVER['QUERY_STRING']

+1

"" , :

    if (isset($_GET['home'])):  
        # show index..  
    elseif (isset($_GET['settings'])):  
        # settings...  
    elseif (isset($_GET['users'])):  
        # user actions..  
    else:  
        # default action or not...  
    endif;

+1

PHP:

switch($_GET){
case !empty($_GET['home']):
   enter code here
break;

case !empty($_GET['settings']):
     enter code here
break;   

default:
     enter code here
break;

}

+1

" " $_SERVER['REQUEST_URI'].

URL-, :

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

PHP:

// 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;
}
0
source

Source: https://habr.com/ru/post/1732592/


All Articles