使用PHP模拟文件结构

Chr*_*row 3 php apache .htaccess url-rewriting url-routing

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

我正在尝试模拟实际上并不存在的文件文件结构.例如,我想要URL: 通过按照本文中的说明编辑我的.htaccess文件www.Stackoverflow.com/jimwiggly来实际显示www.StackOverflow.com/index.php?name=jimwiggly我已经到了一半:PHP:在文件结构中提供没有.php文件的页面:

RewriteEngine on
RewriteRule ^jimwiggly$ index.php?name=jimwiggly
Run Code Online (Sandbox Code Playgroud)

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

Rob*_*itt 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>
Run Code Online (Sandbox Code Playgroud)

然后在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;
   }
}
Run Code Online (Sandbox Code Playgroud)

用得像

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'
Run Code Online (Sandbox Code Playgroud)

现在在MVC中通常喜欢http://site.com/controller/method/param但是在非MVC Style应用程序中你可以做http://site.com/action/sub-action/param

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