PHP URL重写类概述与配置要求
关于Apache服务器中rewrite模块的开启与具体配置细节并非本文重点,读者可参考其他相关技术文章获取详细教程。
本类仅适用于PHP 5.30及以上版本环境。它在继承前代版本快速重定向特性(即独立类文件、全静态调用)的基础上,新增了一项关键功能:允许跨模块调用其他URL中的方法。这一改进使得不同模块或页面间的函数能够以简化的方式进行共享与协作。
以下是用于处理URL重写的.htaccess配置文件的标准写法示例。
//结束代码块代码实现如下:
#-------------- .htaccess start ---------------
RewriteEngine on
RewriteRule !\.(js|ico|gif|jpg|png|css|swf|htm|txt)$ index.php
php_flag magic_quotes_gpc off
php_flag register_globals off
#-------------- .htaccess end ---------------
要启用重写功能,需在站点根目录的index.php文件中引入以下代码片段。正常运行的前提条件包括:1. Apache的重写配置已生效且支持.htaccess;2. 站点根目录下的.htaccess文件已正确设置;3. class.rewrite.php类文件已在index.php的前部被加载;4. 页面模块文件的位置及编写规范无误。
//结束代码块具体代码如下:
//............Rewrite::__config(
$config['path'],/*'http://xxxxx/mysite/'URL基础位置*/
$config['md_path'],/*'c:/phpsite/www/mysite/modules/'模块文件物理目录*/array(
'phpinfo'
));
) ;
//..........接下来介绍模块文件的具体编写规范。
以testPk.php为例。
//结束代码块代码结构如下:
<?php class Rw_testPk extends Rewrite {
//此为前置初始化函数,访问testpk页面时必执行,可用于控制权限或定义全局变量
public static function init(){
//if (!defined('SITE_PASS')){
echo self::$linktag.'
';//self::$linktag表示当前页面的解析路径值,常用于菜单效果或权限控制
//}
} //当访问"http://localhost/testpk/"时将触发此函数
public static function index(){
echo 'test';
} //当访问"http://localhost/testpk/blank"或"http://localhost/testpk/index/blank"时执行,通常"index/"部分可省略
public static function blank(){}
}
?> 以下是核心类class.rewrite.php的实现代码。
//结束代码块代码内容如下:
<?php class Rewrite{
public static $debug = false;//是否开启调试模式
public static $time_pass = 0;//记录模块文件整体执行耗时
public static $version = 2.2;
public static $pretag = 'Rw_';//模块类名的固定前缀
public static $linktag = 'index';//页面链接标记,标识当前解析的链接,可用于菜单高亮或权限判断
protected static $time_start = 0;
protected static $time_end = 0;
protected static $physical_path = '';//模块文件的服务器物理路径
protected static $website_path = '';//模块文件的网站虚拟路径,适用于站点部署在子目录的情况
protected static $ob_contents = '';
protected static $uid = 0;//用于个人主页访问模式,如http://localhost/423/映射为http://localhost/profile?uid=423
//允许的系统函数如$allow_sys_fun=array('phpinfo')那么系统将允许链接访问phpinfo内容了,当http://localhost/phpinfo或http://localhost/......./phpinfo时就会直接执行phpinfo这个函数,不需要phpinfo.php模块文件
private static $allow_sys_fun = array();
private static function __get_microtime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
} //调用Rewrite::__debug(true)可开启调试模式
public static function __debug($d = true){
static::$debug = $d;
} //用于配置路径及允许的内置系统函数
public static function __config($website_path = '',$physical_path = '',$allow_sys_fun = array()){
self::$physical_path = $physical_path;
self::$website_path = $website_path;
self::$allow_sys_fun = $allow_sys_fun;
} //用于输出调试信息
public static function __msg($str){
if(static::$debug){
echo "\n
<pre><code>\n".print_r($str,true)."\n</code></pre>\n";
}
} //记录解析开始时间戳
public static function __start(){
self::$time_start = self::__get_microtime();
} //记录解析结束时间戳
public static function __end($re = false){
self::$time_end = self::__get_microtime();
self::$time_pass = round((self::$time_end - self::$time_start),6) * 1000;
if($re){
return self::$time_pass;
}else{
self::__msg('PASS_TIME: '.self::$time_pass.' ms');
}
} //内部跨模块URL解析调用机制,例如在test1.php中执行Rwrite::__parseurl('/test2/show'),将调用test2.php模块中的show方法
public static function __parseurl($url = '',$fun = '',$data = NULL){
if(!empty($url)&&!empty($fun)){
$p = static::$physical_path;
if(file_exists($p.$url) || file_exists($p.$url.'.php') ){
$part = strtolower(basename( $p.$url , '.php' ));
static::$linktag = $part.'/'.$fun;
$fname = static::$pretag.$part;
if(class_exists($fname, false)){
if(method_exists($fname,$fun)){
return $fname::$fun($data);
} }else{
include( $p.$url );
if( class_exists($fname, false) && method_exists($fname,$fun)){
return $fname::$fun($data);
}
}
}
}
} //核心链接解析函数Rwrite::__parse()在顶级入口index.php中执行,标志着自定义重写流程的启动
public static function __parse($Url = ''){
self::__start();
$p = static::$physical_path;
$w = static::$website_path;
$req_execute = false;
$url_p = empty($Url) ? $_SERVER['REQUEST_URI'] : $Url;
$local = parse_url($w);
$req = parse_url($url_p);
$req_path = preg_replace('|[^\w/.\\\]|','',$req['path']);
$req_para = empty($Url) ? strstr($_SERVER['SERVER_NAME'],'.',true) : 'www';
if(empty($Url) && substr_count($_SERVER['SERVER_NAME'],'.') == 2 && $req_para != 'www'){
self::__goto($req_para,preg_replace('|^'.$local['path'].'|',"",$req_path));
return ;
}else{
$req_path_arr = empty($req_path)?array():preg_split("|[/\\\]+|",preg_replace('|^'.$local['path'].'|',"",$req_path));
$req_fun = array_pop($req_path_arr);
if(substr($req_fun,0,2)=='__'){
$req_fun = substr($req_fun,2);
} $req_path_rearr = array_filter($req_path_arr);
self::__msg($req_path_rearr);
$req_temp = implode('/',$req_path_rearr);
$fname = $req_temp.'/'.$req_fun;
if(!empty($req_fun)&&in_array($req_fun,static::$allow_sys_fun)){
$req_fun();
}else{
if(!empty($req_fun)&&file_exists($p.$fname.'.php') ){
include( $p.$fname.'.php' );
}else{
$fname = empty($req_temp) ? 'index' : $req_temp;
if(file_exists($p.$fname.'.php') ){
include( $p.$fname.'.php' );
}else{
$fname = $req_temp.'/index';
if(file_exists($p.$fname.'.php')){
include( $p.$fname.'.php' );
}else{
//此处针对"个人主页"特殊链接进行定向处理,默认映射至"profile/"
//例如: www.xxx.com/12/ 表示 www.xxx.com/profile/?uid=12 或 www.xxx.com/profile?uid=12
$uid = is_numeric($req_temp) ? $req_temp : strstr($req_temp, '/', true);
$ufun = is_numeric($req_temp) ? 'index' : strstr($req_temp, '/');
if(is_numeric($uid)){
self::$uid = $uid;
if(!isset($_GET['uid'])) $_GET['uid'] = $uid;
$fname = 'profile/'.$ufun;
if(file_exists($p.$fname.'.php')){
include( $p.$fname.'.php' );
}else{
header("location:".$w);
exit();
} }else if(file_exists($p.'index.php')){
$fname = 'index';
include( $p.'index.php' );
}else{
header("location:".$w);
exit();
}
}
}
} $ev_fname = strrpos($fname,'/')===false ? $fname : substr($fname,strrpos($fname,'/')+1);
$ev_fname = static::$pretag.$ev_fname;
if( class_exists($ev_fname, false) && method_exists($ev_fname,$req_fun)){
static::$linktag = $req_fun=='index' ? $fname.'/' : $fname.'/'.$req_fun;
if($req_fun != 'init' && method_exists($ev_fname,'init')){
$ev_fname::init();
} $ev_fname::$req_fun();
}else if( class_exists($ev_fname, false) && method_exists($ev_fname,'index') ){
static::$linktag = $fname.'/';
if(method_exists($ev_fname,'init')){
$ev_fname::init();
} $ev_fname::index();
}else if( $fname != 'index' && class_exists(static::$pretag.'index', false) && method_exists(static::$pretag.'index','index') ){
$ev_fname = static::$pretag.'index';
static::$linktag = 'index/';
if(method_exists($ev_fname,'init')){
$ev_fname::init();
} $ev_fname::index();
}else{
self::__msg('Function Not Exist!');
}
}
} self::__end();
} //支持用户自定义链接解析,通过数据库存储映射关系,如 xiaoming.baidu.com
//数据库中 xiaoming 标签指向某人的博客,则跳转至 www.baidu.com/blog?uid=12 或 uname=xiaoming
public static function __goto($para = '',$path = ''){
$w = static::$website_path;
if(empty($para)){
exit('未知链接,解析失败,不能访问');
} if(class_exists('Parseurl')){
$prs = Parseurl::selectone(array('tag','=',$para));
self::__msg($prs);
if(!empty($prs)){
$parastr = $prs['tag'];
$output = array();
$_GET[$prs['idtag']] = $prs['id'];
parse_str($prs['parastr'], $output);
$_GET = array_merge($_GET,$output);
$path = $prs['type'].'/'.preg_replace('|^/'.$prs['type'].'|','',$path);
self::__msg($path);
header('location:'.$w.$path.'?'.http_build_query($_GET));
exit();
}else{
header("location:".$w);
exit();
} }else{
header("location:".$w);
exit();
}
}
}
?>