2013-01-13 140 views
0

在第一.htaccess,我送urlpublic/index.php清潔網址

RewriteEngine On 
RewriteCond %{REQUEST_FILENAME} -s [OR] 
RewriteCond %{REQUEST_FILENAME} -l [OR] 
RewriteCond %{REQUEST_FILENAME} -d 

RewriteRule ^.*$ - [NC,L] 
RewriteRule ^.*$ public/index.php [NC,L] 

而且我public/index.php

<?php 
// define root path of the site 
if(!defined('ROOT_PATH')){ 
define('ROOT_PATH','../'); 
} 

require_once ROOT_PATH.'function/my_autoloader.php'; 

use application\controllers as controllers; 

$uri=strtolower($_SERVER['REQUEST_URI']); 
$actionName=''; 
$uriData=array(); 
$uriData=preg_split('/[\/\\\]/',$uri); 

$actionName = (!empty($uriData[3])) ? preg_split('/[?].*/', $uriData[3]): '' ; 
$actionName =$actionName[0]; 
$controllerName = (!empty($uriData[2])) ? $uriData[2] : '' ; 

switch ($controllerName) { 
case 'manage': 
    $controller = new Controllers\manageController($controllerName,$actionName); 
    break; 
default: 
    die('ERROR WE DON\'T HAVE THIS ACTION!'); 
    exit; 
    break; 
    } 

// function dispatch send url to controller layer 
$controller->dispatch(); 
?> 

我有這樣的目錄:

  • 應用
    • 控制器
    • 車型
    • 視圖
  • 公共
    • css
    • java script
    • 的index.php
  • .htaccess

我想幹淨URL例如localhost/lib/manage/id/1而不是localhost/lib/manage?id=1,我該怎麼辦?

+0

在這個URL'localhost/lib/manage/id/1'中哪些文件夾名稱字符串是動態的,哪些是固定的? –

回答

1

使用您當前的重寫規則,所有內容都已重定向到您的index.php文件。而且,正如您已經在做的那樣,您應該解析URL以查找所有這些URL參數。這叫做路由,大多數PHP框架都是這樣做的。在「/」

array(
    'controller' => 'manage', 
    'id' => 1 
) 

我們可以簡單地做到這一點,首先拆分的URL,然後遍歷它來尋找價值:通過一些簡單的解析,您可以將localhost/lib/manage/id/1到一個數組

$output = array(); 
$url = split('/', $_SERVER['REQUEST_URI']); 
// the first part is the controller 
$output['controller'] = array_shift($url); 

while (count($url) >= 2) { 
    // take the next two elements from the array, and put them in the output 
    $key = array_shift($url); 
    $value = array_shift($url); 
    $output[$key] = $value; 
} 

現在,$output數組包含一個您想要的鍵值對。儘管請注意代碼可能不是很安全。這只是展示概念,而不是真正的生產就緒代碼。

+0

當我有2個ID,我該怎麼辦?以及如何可以找到哪個ID? – navid

+1

我編輯了我的答案,使其更清楚如何實際解析URL。 – kokx

+0

謝謝,但現在我有'css'文件地址和圖像地址的問題,我該如何解決我的問題? – navid

0

您可以通過捕獲URL的一部分並將其作爲查詢字符串來執行此操作。

RewriteRule /lib/manage/id/([0-9]+) /lib/manage?id=$1 [L] 

括號內的字符串將被放入$ 1變量中。如果您有多個(),它們將被放入$ 2,$ 3等等。