代码之家  ›  专栏  ›  技术社区  ›  Patrick Desjardins

字符串参数的漂亮url

  •  3
  • Patrick Desjardins  · 技术社区  · 14 年前

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

    我计划有一个漂亮的url来将以前的url转换为: /profile/whatever/2

    我知道我必须使用.htaccess并将所有内容重定向到index.php。那很好。

    我的问题更多的是index.php(前控制器)。我怎样才能重建 $_GET["info"] $_GET["anotherparam"] 能够继续使用所有使用 $_GET[...] 在他们的页面上?

    我必须用一些代码重新构建get-in头文件吗?还是必须去掉所有的 […] 在每个页面上创建我自己的数组 / 分配给如下对象: $myParam["info"] = "whatever" 比在页面中使用 $myParam[] 而不是 $_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。因为我已经使用了这个结构: 索引?page=45&info=whatever&anotherparam=2 什么都没坏。但现在我要用 /个人资料/随便什么/2 在切换的情况下,我可以决定 include(..) 但问题是所有的get参数。如何将它们构建为可以从所有页面访问$GET[]?

    2 回复  |  直到 14 年前
        1
  •  3
  •   Mathieu    14 年前
    $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];
    }
    

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

    如果你不想你有两个解决方案: -使用路径like/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
  •  0
  •   streetparade    14 年前

    改用switch语句。还要记住修改.htaccess

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