2010-06-29 105 views
3

我在共享的Apache Web服务器上运行PHP。我可以编辑.htaccess文件。使用PHP模拟文件结构

我试图模拟一个实际上并不存在的文件文件结构。例如,我想对于网址: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 

这只要很好地工作作为地址栏仍然显示www.Stackoverflow.com/jimwiggly和正确的页面加载,但是,我所有的相对链接保持不变。我可以重新插入并在每个链接前插入<?php echo $_GET['name'];?>,但似乎可能有比这更好的方法。此外,我怀疑我的整个方法可能会关闭,我应该以不同的方式进行讨论吗?

回答

6

我认为最好的方法是采用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风格的应用程序,你可以做http://site.com/action/sub-action/param

希望这有助于你与你的应用向前发展。

+0

+1或更好的使用MVC;)。 – 2010-06-29 21:57:21

+0

是的,我会解释说,对他来说,但似乎他已经中途抛出他的应用程序,所以只给了最好的答案,而无需重新编码所有的应用程序。 – RobertPitt 2010-06-29 21:59:19

+0

@RobertPitt - 是的,我把这个网站放在2004年,随着时间的推移,如果我不得不再做一遍,我会使用一个框架。但从现在开始,像这样的影响会更小。非常感谢。 – 2010-06-29 22:03:50