【问题标题】:Simulate file structure with PHP用 PHP 模拟文件结构
【发布时间】:2011-03-09 20:49:45
【问题描述】:

我在共享的 Apache Web 服务器上运行 PHP。我可以编辑 .htaccess 文件。

我正在尝试模拟一个实际上并不存在的文件文件结构。例如,我希望 URL:www.Stackoverflow.com/jimwiggly 实际显示 www.StackOverflow.com/index.php?name=jimwiggly 我通过按照这篇文章中的说明编辑我的 .htaccess 文件到达了一半:PHP: Serve pages without .php files in file structure

RewriteEngine on
RewriteRule ^jimwiggly$ index.php?name=jimwiggly

只要 URL 栏仍然显示 www.Stackoverflow.com/jimwiggly 并且正确的页面加载,这很好用,但是,我的所有相关链接都保持不变。我可以返回并在每个链接之前插入<?php echo $_GET['name'];?>,但似乎可能有比这更好的方法。此外,我怀疑我的整个方法可能会失败,我应该采取不同的方式吗?

【问题讨论】:

    标签: php apache .htaccess url-rewriting url-routing


    【解决方案1】:

    我认为最好的方法是采用 MVC 样式的 url 操作,使用 URI 而不是参数。

    在您的 htaccess 中使用如下:

    <IfModule mod_rewrite.c>
        RewriteEngine On
        #Rewrite the URI if there is no file or folder
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule ^(.*)$ index.php?/$1 [L]
    </IfModule>
    

    然后在您的 PHP 脚本中,您想开发一个小类来读取 URI 并将其拆分为段,例如

    class URI
    {
       var $uri;
       var $segments = array();
    
       function __construct()
       {
          $this->uri = $_SERVER['REQUEST_URI'];
          $this->segments = explode('/',$this->uri);
       }
    
       function getSegment($id,$default = false)
       {
          $id = (int)($id - 1); //if you type 1 then it needs to be 0 as arrays are zerobased
          return isset($this->segments[$id]) ? $this->segments[$id] : $default;
       }
    }
    

    使用喜欢

    http://mysite.com/posts/22/robert-pitt-shows-mvc-style-uri-access

    $Uri = new URI();
    
    echo $Uri->getSegment(1); //Would return 'posts'
    echo $Uri->getSegment(2); //Would return '22';
    echo $Uri->getSegment(3); //Would return 'robert-pitt-shows-mvc-style-uri-access'
    echo $Uri->getSegment(4); //Would return a boolean of false
    echo $Uri->getSegment(5,'fallback if not set'); //Would return 'fallback if not set'
    

    现在在 MVC 中通常有 http://site.com/controller/method/param,但在非 MVC 风格的应用程序中你可以这样做 http://site.com/action/sub-action/param

    希望这可以帮助您继续申请。

    【讨论】:

    • 是的,我会向他解释这一点,但似乎他已经完成了一半的申请,所以只需给出最佳答案,而无需重新编码所有申请。
    • @RobertPitt - 是的,我在 2004 年建立了这个网站,它随着时间的推移而发展,如果我不得不重新做一次,我会使用一个框架。但从现在开始,像这样影响较小的东西会更好。非常感谢。
    • @RobertPitt - 好的,我是否只使用“Uri”对象返回并编辑所有相关链接?
    • $Uri 与 get 一样使用,但使用 -> 而不是数组,因此 $_GET[0] 与 $Uri->getSegment(0); 相同;在 URI index.php?/first/second/third/etc/etc 中传递的第一项,我只是对 getSegment() 方法做了一个小编辑
    • @RobertPitt - 太酷了,所以基本上我还是需要回去编辑我所有的链接,对吧?
    猜你喜欢
    • 1970-01-01
    • 2017-01-15
    • 2016-02-07
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 2011-04-22
    相关资源
    最近更新 更多