1.什么是php的路由机制

1、路由机制就是把某一个特定形式的URL结构中提炼出来系统对应的参数。举个例子,如:http://main.wopop.com/article/1  其中:/article/1  -> ?_m=article&id=1。2、然后将拥有对应参数的URL转换成特定形式的URL结构,是上面的过程的逆向过程。

2.PHP的URL路由方式

总体来说就是:获取路径信息->处理路径信息URL路由方式:

第一种是通过url参数进行映射的方式,一般是两个参数,分别代表控制器类和方法比如index.php?c=index&m=index映射到的是index控制器的index方法。

第二种,是通过url-rewrite的方式,这样的好处是可以实现对非php结尾的其他后缀进行映射,当然通过rewrite也可以实现第一种方式,不过纯使用rewrite的也比较常见,一般需要配置apache或者nginx的rewrite规则

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

第三种,就是通过pathinfo的方式,所谓的pathinfo,就是形如这样的url。xxx.com/index.php/c/index/aa/cc,apache在处理这个url的时候会把index.php后面的部分输入到环境变量$_SERVER['PATH_INFO'],它等于/c/index/aa/cc。然后我们的路由器再通过解析这个串进行分析就可以了,后面的部分放入到参数什么地方的,就依据各个框架不同而不同了。

3. 一个简单的PHP路由实现

3.1 修改htaccess文件

编写服务器apache或IIS自带的rewrite文件,将URL结构导入指定文件比如:index.php。开启rewrite:htaccess文件是Apache服务器中的一个配置文件,它负责相关目录下的网页配置。启用.htaccess,需要修改apache/conf/httpd.conf,启用AllowOverride,并可以用AllowOverride限制特定命令的使用。
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
改为
<Directory />
Options FollowSymLinks
AllowOverride All
</Directory>

然后我写了这样的rewrite:
RewriteEngine on #rewriteengine为重写引擎开关on为开启off为关闭
#RewriteCond $1 !^(index.php.php|images|robots.txt)
RewriteRule ([a-zA-Z]{1,})-([0-9]{1,}).html$ sharexie/test.php?action=$1&id=$2
#([a-zA-Z]{1,})-([0-9]{1,}).html$是规则,sharexie/test.php?action=$1&id=$2是要替换的格式,$1代表第一个括号匹配的值,$2代表第二个。
上面的代码就是将URL结构导入sharexie/test.php中。把这些保存为.htaccess文件放在网站的根目录就行了。test.php
<?php
echo '你的Action是:' . $_GET['action'];
echo '<br/>';
echo '你的ID是:' . $_GET['id'];
?>

好了,我们现在在浏览器中输入:

127.0.0.1/view-12.html

输出的是:

你的Action是:view

你的ID是:12

1、讲解一下RewriteRule:

RewriteRule是重写规则,支持正则表达式的,上面的([0-9]{1,})是指由数字组成的,$是结束标志,说明是以数字结束!

2、RewriteRule配置参数

1) R 强制外部重定向

2) F 禁用URL,返回403HTTP状态码。

3) G 强制URL为GONE,返回410HTTP状态码。

4) P 强制使用代理转发。

5) L 表明当前规则是最后一条规则,停止分析以后规则的重写。

6) N 重新从第一条规则开始运行重写过程。

7) C 与下一条规则关联

8) T=MIME-type(force MIME type) 强制MIME类型

9) NS  只用于不是内部子请求

10) NC 不区分大小写

11) QSA 追加请求字符串

12) NE 不在输出转义特殊字符   %3d$1  等价于 =$1

举例:

1、将xianglc将定到 index.php?c=myuser&m=itime&domain=xianglc

RewriteRule ^([a-zA-Z0-9]){6,20}/?$ index.php?c=myuser&m=itime&domain=$0 [L]

2、#RewriteRule ^/index.html$ /1.php [L]

RewriteRule ^/index-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?)$ $9&a=$1&b=$2&c=$3&d=$4&e=$5&f=$6&g=$7&h=$8 [C,NC]
RewriteRule ^(.*?)-(.*?)-(.*?)-(.*?)-(.*?)-(.*?).html(.*?)$ /1.php?$7&i=$1&j=$2&k=$3&l=$4&m=$5&n=$6 [QSA,L,NC]

Php内容:

3.2 一个路由解析器,用来解析规则,匹配和转换URL。

先将所有的链接转到index.php中,在index.php中进行路由分发,按照类和方法分配到相应的类文件中的函数上去。用$_SERVER['REQUEST_URI']取出URL中的www.xx.com/后面的部分,按照相关规则分别区分为class和mothod以及参数key=>value的值。最后include该类文件,执行其中的函数。

实例如下:

<?php
error_reporting(0);
date_default_timezone_set("Asia/Shanghai");
$_DocumentPath = $_SERVER['DOCUMENT_ROOT'];
$_RequestUri = $_SERVER['REQUEST_URI'];
$_UrlPath = $_RequestUri;
$_FilePath = __FILE__;
$_AppPath = str_replace($_DocumentPath, '', $_FilePath);    //==>routerindex.php
$_AppPathArr = explode(DIRECTORY_SEPARATOR, $_AppPath);
for ($i = 0; $i < count($_AppPathArr); $i++) {
       $p = $_AppPathArr[$i];
       if ($p) {
           $_UrlPath = preg_replace('/^/'.$p.'//', '/', $_UrlPath, 1);
       }
    }
   $_UrlPath = preg_replace('/^//', '', $_UrlPath, 1);
   $_AppPathArr = explode("/", $_UrlPath);
   $_AppPathArr_Count = count($_AppPathArr);
   $arr_url = array(
       'controller' => 'sharexie/test',
       'method' => 'index',
       'parms' => array()
   );
   $arr_url['controller'] = $_AppPathArr[0];
   $arr_url['method'] = $_AppPathArr[1];
   if ($_AppPathArr_Count > 2 and $_AppPathArr_Count % 2 != 0) {
       die('参数错误');
   } else {
       for ($i = 2; $i < $_AppPathArr_Count; $i += 2) {
           $arr_temp_hash = array(strtolower($_AppPathArr[$i])=>$_AppPathArr[$i + 1]);
           $arr_url['parms'] = array_merge($arr_url['parms'], $arr_temp_hash);
       }
   }
   $module_name = $arr_url['controller'];
   $module_file = $module_name.'.class.php';
   $method_name = $arr_url['method'];
   if (file_exists($module_file)) {
       include $module_file;
       $obj_module = new $module_name();
       if (!method_exists($obj_module, $method_name)) {
           die("要调用的方法不存在");
       } else {
           if (is_callable(array($obj_module, $method_name))) {
               $obj_module -> $method_name($module_name, $arr_url['parms']);
               $obj_module -> printResult();
           }
       }
   } else {
       die("定义的模块不存在");
   }
?>

参考文档:http://httpd.apache.org/docs/2.2/rewrite/http://www.cnblogs.com/xiangxiaodong/archive/2012/07/19/2600138.html

转自:http://www.cnblogs.com/fredshare/archive/2012/09/17/2688944.html