search
HomeBackend DevelopmentPHP TutorialPHP fast url rewriting updated version [requires PHP 5.30 or above]_PHP tutorial

Opening and setting up the rewrite module of apache is not the subject of this article. Please see other articles for detailed explanations.
This class can only be used in versions above PHP 5.30. It inherits the characteristics of fast redirection from the previous version (single class, all Using static calling), a very important function and attribute is added to call modules in other URLs, which also enables simplified sharing of functions between modules or between pages.
.htaccess file writing method:

Copy code The code is as follows:

#------------- .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 ---------------

Introduction of rewriting function: write the following code at the end of index.php in the root directory of the site, and rewriting will be enabled (normal conditions: 1. Apache rewrite configuration is successful, and .htaccess support is enabled. 2. Site The .htaccess file in the root directory is set up. 3. The class.rewrite.php class file is loaded in the front part of index.php. 4. The page module file location and writing are correct):
Copy code The code is as follows:

//............
Rewrite::__config(
$config[' path'],/*'http://xxxxx/mysite/'URL base location*/
$config['md_path'],/*'c:/phpsite/www/mysite/modules/'Module file physics Directory*/
array(
'phpinfo'
)
);
Rewrite::__parse();
//......

Module file writing method:
testPk.php
Copy code The code is as follows:

< ;?php
class Rw_testPk extends Rewrite {
//This is the leading function. As long as the testpk page is accessed, this will definitely be executed. It can be used to control function access permissions within this page or global variables of this page
public static function init(){
//if (!defined('SITE_PASS')){
echo self::$linktag.'
';//self::$linktag is Page parsing location path value, will be used frequently.
//}
}
//When accessing "http://localhost/testpk/", it will be executed
public static function index(){
echo 'test';
}
//When accessing "http://localhost/testpk/blank", it will be executed or written as "http://localhost/testpk/index/blank". index/" can be omitted
public static function blank(){}
}
?>

class.rewrite.php;
Copy code The code is as follows:

class Rewrite{
public static $debug = false;//Whether to turn on debugging
public static $time_pass = 0;//Get the overall execution time of the module file
public static $version = 2.2;
public static $pretag = 'Rw_';//Name prefix of module file class
public static $linktag = 'index';//Page link tag, used to mark What is parsed is that link, which can be used to control various menu effects and link access permissions
protected static $time_start = 0;
protected static $time_end = 0;
protected static $physical_path = '';// The physical path of the module file
protected static $website_path = '';//The site path of the module file, because the site may be enlarged to a subdirectory of the site, such as: http://localhost/site/mysite
protected static $ob_contents = '';
protected static $uid = 0;//To access the personal homepage such as http://localhost/423/, access http://localhost/profile?uid=423
//Allowed system functions such as $allow_sys_fun=array('phpinfo') then the system will allow links to access phpinfo content. When http://localhost/phpinfo or http://localhost/...../phpinfo The phpinfo function will be executed directly without the phpinfo.php module file
private static $allow_sys_fun = array();
private static function __get_microtime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
//Set debugging Rewrite::__debug(true);
public static function __debug($d = true){
static::$debug = $d;
}
//Configuration path and allowed functions
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 ;
}
//Debug function
public static function __msg($str){
if(static::$debug){
echo "n
n".print_r( $str,true)."n
n";
}
}
//Parse start time
public static function __start(){
self::$time_start = self::__get_microtime();
}
//Parse end time
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');
}
}
//Internal cross-module url parsing call, as in If the sentence Rwrite::__parseurl('/test2/show') is executed in the test1.php module page, the show method (the method of the Rw_test2 class) in the test2.php module page will be called.
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);
}
}
}
}
}
//The core link parsing function Rwrite::__parse(); is executed in the top-level rewrite core directional target index.php, which means that Rwrite custom rewriting is turned on
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{
//This is a special link to "personal homepage" directed to "profile/", you can modify it yourself
//For example: www.xxx.com/12/ will mean www. xxx.com/profile/?uid=12 or 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();
}
//Here is the parsing of user-defined links (using the parsed value stored in the database) such as: xiaoming.baidu.com
//xiaoming this in the database If the tag points to a person's blog, it will go to www.baidu.com/blog?uid=12 or www.baidu.com/blog?uname=xiaoming (this depends on how you design the database)
public static function __goto( $para = '',$path = ''){
$w = static::$website_path;
if(empty($para)){
exit('Unknown link, parsing failed, cannot access');
}
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();
}
}
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/321736.htmlTechArticleOpening and setting up the rewrite module of apache is not the subject of this article. Please see other articles for details. This class can only be used in PHP Only versions 5.30 and above can be used, inheriting the fast redirection of the previous version...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.