【问题标题】:Pretty URL to string parameters字符串参数的漂亮 URL
【发布时间】:2011-01-22 22:11:42
【问题描述】:

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

我打算用漂亮的 url 将之前的 url 转换为:/profile/whatever/2

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

我的问题更多在于 index.php(前端控制器)。如何重新构建 $_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[] 从所有页面访问?

【问题讨论】:

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


    【解决方案1】:
    $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];
    }
    

    【讨论】:

    【解决方案2】:

    改为使用 switch 语句。还记得修改你的 .htaccess

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

    【讨论】:

      猜你喜欢
      • 2013-09-14
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 2012-01-21
      • 2017-04-16
      • 2016-02-17
      • 2015-01-15
      • 2011-03-12
      相关资源
      最近更新 更多