2010-06-29 108 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