代码之家  ›  专栏  ›  技术社区  ›  Chris Dutrow

用PHP模拟文件结构

  •  3
  • Chris Dutrow  · 技术社区  · 16 年前

    我在共享的apacheweb服务器上运行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
    

    正确的页面加载,但是,我的所有相关链接保持不变。我可以回去插入 <?php echo $_GET['name'];?> 在每一个环节之前,但似乎有比这更好的方法。此外,我怀疑我的整个方法可能是关闭的,我应该采取不同的做法吗?

    1 回复  |  直到 9 年前
        1
  •  7
  •   RobertPitt    16 年前

    在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'
    

    http://site.com/controller/method/param 但是在非MVC风格的应用程序中 http://site.com/action/sub-action/param

    希望这有助于你的申请。