用PHP模拟文件结构

用PHP模拟文件结构,php,apache,.htaccess,url-rewriting,url-routing,Php,Apache,.htaccess,Url Rewriting,Url Routing,我正在共享的ApacheWeb服务器上运行PHP。我可以编辑.htaccess文件 我试图模拟一个实际上不存在的文件结构。例如,我想让URL:www.Stackoverflow.com/jimwiggy实际显示www.Stackoverflow.com/index.php?name=jimwiggy我按照本文中的说明编辑了.htaccess文件,完成了一半: 只要URL栏仍然显示www.Stackoverflow.com/jimwiggy,并且加载了正确的页面,就可以很好地工作,但是,我的所有相

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

我试图模拟一个实际上不存在的文件结构。例如,我想让URL:
www.Stackoverflow.com/jimwiggy
实际显示
www.Stackoverflow.com/index.php?name=jimwiggy
我按照本文中的说明编辑了.htaccess文件,完成了一半:


只要URL栏仍然显示
www.Stackoverflow.com/jimwiggy
,并且加载了正确的页面,就可以很好地工作,但是,我的所有相关链接都保持不变。我可以返回并在每个链接之前插入
,但似乎有更好的方法。此外,我怀疑我的整个方法可能已经过时了,我是否应该换一种方式来处理这个问题?

我认为最好的方法是对URI而不是参数采用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>

现在在MVC中,通常会出现类似的情况,但在非MVC风格的应用程序中,您可以这样做


希望这有助于您的应用程序向前推进。

是的,我当然会向他解释,但他似乎已经把应用程序扔了一半,所以只给出了最好的答案,而不必重新编写所有应用程序。@RobertPitt-是的,我早在2004年就创建了这个网站,它随着时间的推移而不断发展,如果我必须再做一遍,我会使用一个框架。但从现在开始,像这样影响较小的东西会起到更好的作用。非常感谢。@RobertPitt-好的,那么我是否只需要使用“Uri”对象返回并编辑所有的相关链接呢?$Uri的使用方式与get一样,但使用了->而不是数组,因此$\u get[0]与$Uri->getSegment(0)相同;在URI index.php中传递的第一项?/first/second/third/etc/etc,我刚刚对getSegment()做了一个小编辑Method@RobertPitt-那很酷,所以基本上我还需要回去编辑我所有的链接,对吗?
<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>
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;
   }
}
$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'