相当于字符串参数的URL

时间:2010-03-02 20:52:31

标签: php apache url url-rewriting front-controller

我有一个使用此风格的网站:/index.php?page=45&info=whatever&anotherparam=2

我计划将上一个网址转换为:/profile/whatever/2

我知道我必须使用.htAccess并将所有内容重定向到index.php。没关系。

我的问题更多在index.php(Front Controller)中。如何构建$_GET["info"]$_GET["anotherparam"]以便能够继续使用在其页面中使用$_GET[...]的所有现有代码?

我是否必须使用某些代码在标头中构建GET,或者我必须通过创建我自己的数组来清除每个页面上的所有$_GET[...],并将/解析为分配如下内容:$myParam["info"] = "whatever",而不是使用$myParam[]代替$_GET[]

我不想修改所有使用$_GET[]

的网页

编辑:

我的.htAccess看起来像:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ index.php [NC,L]

不存在的一切都转到index.php。因为我已经使用了这个结构:/index.php?page=45&info=whatever&anotherparam=2没有任何东西被打破。但现在我将使用/profile/whatever/2,在切换情况下,我可以确定include(..)的页面,但问题在于所有GET参数。如何构建它们以使用$ _GET []?

从所有页面进行访问

2 个答案:

答案 0 :(得分:3)

$path = ... // wherever you get the path $_SERVER[...], etc.
            // eg: /profile/wathever

$segments = split ($path);

$segments_name = Array ('page', 'info', 'anotherparam');
for($i=0;$i  < count ($segments); $i++) {
  $_GET[$segments_name[$i]] = $segments[$i];
}

使用此解决方案,您必须始终在相同位置使用相同的参数

如果您不希望有两个解决方案:   - 使用/ page / profile / info / wathever之类的路径   - 使用路由器系统(为此我建议您使用框架而不是手动完成)

编辑:第二个解决方案

$path = ... // wherever you get the path $_SERVER[...], etc.
            // eg: /page/profile/info/wathever
$segments = split ($path);

for($i=0;$i  < count ($segments); $i+=2) {
  $_GET[$segments[$i]] = $segments[$i+1];
}

答案 1 :(得分:0)

请改用switch语句。还记得修改.htaccess

<?php
switch ($_GET) {
    case "home":
     header('Location: /home/');
        break;
    case "customer":
        header('Location: /customer/');
        break;
    case "profile":
        header('Location: /profile/');
        break;
}
?>
相关问题