当前位置: 首页 > 编程文章 >

PHP快速URL重写类:实现模块间函数共享与静态调用

PHP快速URL重写类:实现模块间函数共享与静态调用

作者:周禾时间:2026-07-21 11:09:51浏览:376

该PHP URL重写类专为5.30以上版本设计,通过静态方法调用简化页面逻辑。它支持模块间函数直接共享,无需实例化对象。配合.htaccess规则,可将请求统一指向index.php进行核心解析,实现类似MVC的路由功能并支持个人主页等特殊链接定向。

本文目录展开

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();
        }
    }
}
?>

上一篇
Linux下安装PHP memcached客户端完整指南

本文介绍在Linux环境下为PHP安装memcached客户端的完整流程。首先需下载并编译安装libmemcached库,推荐使用1.0.16版本以避免1.0.17版本的已知Bug;随后通过PECL安装memcached PHP扩展,配置时需指定libmemcached路径并禁用SASL支持。最后重启Nginx和PHP服务,并通过phpinfo()函数验证扩展是否加载成功。

下一篇
PHP natsort自然排序内核源码解析

PHP的natsort函数实现了符合人类直觉的自然排序算法,能够正确处理包含数字的字符串。通过深入ext/standard/array.c源码可知,该函数的核心比较逻辑委托给ext/standard/strnatcmp.c中的strnatcmp_ex函数。源码显示,非字符串类型会被转换为字符串后再进行比较,最终通过zend_hash_sort调用快速排序完成数组元素的重新排列。

相关文章

更多
IIS配置页面重写以去除URL后缀名

本文介绍在Windows IIS环境中利用Microsoft提供的url-rewrite2组件实现URL重写,从而去除浏览器地址栏中的.php等文件后缀。主要步骤包括安装Platform Installer及url-rewrite2模块、重启IIS服务加载功能、创建.htaccess配置文件定义RewriteEngine和RewriteBase规则,并通过IIS管理界面导入该规则并应用,最终实现用户输入无后缀URL时服务器自动补全实际路径的效果。

2025.08.10 820
ThinkPHP去除URL中index.php的配置方法

在ThinkPHP框架中,通过配置URL_MODEL为2可启用PATHINFO模式以去除URL中的index.php。在Apache环境下需启用mod_rewrite模块并配置.htaccess文件;而在新浪SAE环境中,则需在config.yaml中定义rewrite规则。若使用企业版等自定义配置,需注意覆盖默认值以避免模式未生效。

2025.05.07 815
PHP输出缓冲与URL重写函数详解

本文介绍PHP中用于控制输出缓冲和URL重写的核心函数。重点解析ob_start开启缓冲、ob_flush等函数处理缓存状态,以及ob_gzhandler实现压缩输出的方法。同时说明output_add_rewrite_var如何向URL和表单添加参数,并演示output_reset_rewrite_vars重置重写规则的效果。

2026.01.23 789
ThinkPHP pathinfo访问模式与URL重写配置详解

本文总结ThinkPHP中pathinfo的两种模式、四种路径访问模式及URL重写方法。通过修改config目录下的URL_MODEL值,可切换普通、pathinfo、rewrite伪静态及兼容模式。启用rewrite需开启Apache模块、设置AllowOverride为All并配置.htaccess文件,虽利于SEO但会增加服务器负载。

2025.10.08 747
ThinkPHP6.0 URL重写去除index.php的正确配置方法

本文解决ThinkPHP6.0在Apache环境下通过URL重写隐藏入口文件index.php时遇到的配置错误。重点指出官网示例中RewriteRule末尾缺少PATH_INFO环境变量导致的404问题,并提供正确的.htaccess配置代码及Apache AllowOverride设置步骤。

2025.03.13 610
Apache配置去除ThinkPHP URL中的index.php

本文介绍如何在Apache服务器环境下,通过修改配置文件和添加.htaccess规则,将ThinkPHP应用URL中的index.php移除。主要步骤包括启用mod_rewrite模块、设置AllowOverride为All、配置项目URL_MODEL为2,以及编写正确的RewriteRule规则。此方法可实现更简洁的URL结构,提升用户体验。

2026.07.25 603

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。