带有 GET 请求的 PHP 开关

2022-01-04 00:00:00 switch-statement get php

我正在为我的网站构建一个简单的管理区域,我希望 URL 看起来像这样:

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
http://mysite.com/admin/?users

但我不确定如何检索请求的页面,然后显示所需的页面.我在我的交换机上试过这个:

But I am not sure how I would retrieve what page is being requested and then show the required page. I tried this in my switch:

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

但我收到此错误:

致命错误:第 40 行无法使用 [] 读取 C:path owebdirectoryadminindex.php

有什么办法可以解决这个问题吗?我想避免为 GET 请求设置值,例如:

Is there any way around this? I want to avoid setting a value to the GET request, like:

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

如果你知道我的意思.谢谢.:)

If you know what I mean. Thanks. :)

推荐答案

使用 $_SERVER['QUERY_STRING'] –包含 ? 之后的位:

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/

只需使用 explode() 将查询字符串拆分为段,获取第一个并将其余部分作为方法的参数传递:

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;
}

这种方法在许多采用 MVC 模式的框架中都很流行.完全摆脱 ? 的另一个步骤是在 Apache 服务器上使用 mod_rewrite,但我认为这有点超出了这个问题的范围.

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.

相关文章