PHP switch with GET request(带有 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.
这篇关于带有 GET 请求的 PHP 开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带有 GET 请求的 PHP 开关
				
        
 
            
        基础教程推荐
- php中的PDF导出 2022-01-01
 - PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
 - php 7.4 在写入变量中的 Twig 问题 2022-01-01
 - Web 服务器如何处理请求? 2021-01-01
 - 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
 - Yii2 - 在运行时设置邮件传输参数 2022-01-01
 - 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
 - 将变量从树枝传递给 js 2022-01-01
 - php中的foreach复选框POST 2021-01-01
 - 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				