PHP切换GET请求 [英] PHP switch with GET request
问题描述
我为我的网站构建了一个简单的管理区域,我希望网址看起来有点像这样:
$ b http: //mysite.com/admin/?home
http://mysite.com/admin/?settings
http://mysite.com/admin/?users
但我不知道如何检索正在请求的页面,然后显示所需的页面。我在我的开关中试过这个:
switch($ _ GET [])
{
case'home ':
echo'admin home';
休息;
}
但是我得到这个错误:
致命错误:无法使用[]读取第40行的C:\path\to\web\directory\admin\index.php
有没有办法解决这个问题?我想避免给GET请求设置一个值,如:
http://mysite.com/admin/?action = home
如果您知道我的意思。谢谢。 :)
使用 $ _ SERVER ['QUERY_STRING']
–它包含?
之后的位:
switch($ _ SERVER [ 'QUERY_STRING']){
'home':
echo'admin home';
休息;
}
您可以更进一步使用此方法并使用以下URL:
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);
休息;
}
这种方法在很多采用MVC模式的框架中很流行。完全摆脱?
的额外步骤是在Apache服务器上使用 mod_rewrite
,但我认为这有点儿超出这个问题的范围。
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;
}
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 avoid setting a value to the GET request, like:
http://mysite.com/admin/?action=home
If you know what I mean. Thanks. :)
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.
这篇关于PHP切换GET请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!