2013-01-13 144 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等等。