2010-12-07 82 views
0

我有一個url像URL處理PHP

http://something.com/abc/def/file.php/arguments 

這只是執行final.php和/參數傳遞給$ _ SERVER [ 'PATH_INFO']變量。

我想執行相同,但沒有「.PHP」即,

http://something.com/abc/def/file/arguments 

我猜我需要添加東西的http.conf,還是......?

回答

3

的.htaccess是你的朋友

Options +FollowSymLinks 
RewriteEngine on 
RewriteRule file/(.*) file.php?param=$1 
2

我認爲最好的辦法是採用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設計模式與URL重寫有任何關係。 – netcoder 2010-12-07 20:06:50

+0

感謝您的快速反應。但是,我有代碼庫,我只需要讓我的問題工作,就必須在htaccess中添加什麼有什麼建議? – vkris 2010-12-07 20:08:19

0

此URL風格可以通過url_rewrite(稱爲URL重寫)來管理,它可以與.htaccess文件的Apache服務器來完成。

做到這一點,你需要寫這個你.htaccess文件:

RewriteEngine On 
RewriteRule ^http://something.com/every/name/you/like/(arguments)/?$ server_folder/page.php?argument_var=$1 

第一個代碼塊,rapresents用戶調用頁面:

^http://something.com/every/name/you/like/(arguments)/?$ 

第二塊是您要撥打的實際頁面,其中$1()內的var值

server_folder/page.php?argument_var=$1 

如果用戶必須到一個URL這裏的參數是數字只是你應該插入:

^http://something.com/every/name/you/like/([0-9])/?$ 

如果用戶必須到一個URL這裏的參數是字母只有你應該插入:

^http://something.com/every/name/you/like/([a-zA-Z])/?$ 

要正確使用此URL樣式,您需要了解一些常規表達式,如in this link

你可以找到有用的this table幫助你瞭解更多的東西。

注意,你可以寫不同的URL,而不是像真正的網頁名稱:

^http://something.com/love/([a-zA-Z0-9])/?$ section/love/search.php?$1 

這應該是隱藏服務器頁面是有用的。