使用PHP模拟文件结构

时间:2010-06-29 21:41:06

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

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

我正在尝试模拟实际上并不存在的文件文件结构。例如,我希望网址: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'];?>,但似乎可能有更好的方法。另外,我怀疑我的整个方法可能都会关闭,我是否应该以不同的方式解决这个问题?

1 个答案:

答案 0 :(得分:7)

我认为最好的方法是采用带有URI而不是params的MVC样式url操作。

在你的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 Style应用程序中你可以http://site.com/action/sub-action/param

希望这可以帮助您推进应用程序。