search
HomeBackend DevelopmentPHP TutorialPHP fast url rewriting example code

It can only be used with version 5.30 or above. It inherits the characteristics of fast redirection of the previous version (separate class, all using static calls), and adds a very important function and attribute, which can call modules in other URLs, which also makes Simplified sharing of functions between modules or pages is achieved. .htaccess file writing method:

  1. #------------- .htaccess start ---------------
  2. RewriteEngine on
  3. RewriteRule !.(js|ico |gif|jpg|png|css|swf|htm|txt)$ index.php
  4. php_flag magic_quotes_gpc off
  5. php_flag register_globals off
  6. #------------- .htaccess end ---- -----------
Copy code

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's rewrite configuration is successful, and .htaccess support is enabled. 2. The .htaccess file in the site root directory is set up. 3. The class.rewrite.php class file is loaded in the front part of index.php. 4. Page module The file location and writing are correct): code show as below:

  1. //......
  2. Rewrite::__config(
  3. $config['path'],/*'http://xxxxx/mysite/'URL base location */
  4. $config['md_path'],/*'c:/phpsite/www/mysite/modules/'module file physical directory*/
  5. array(
  6. 'phpinfo'
  7. )
  8. );
  9. Rewrite::__parse( );
  10. //..........
Copy code

Module file writing method: testPk.php

  1. class Rw_testPk extends Rewrite {
  2. //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.
  3. public static function init(){
  4. //if (!defined('SITE_PASS')){
  5. echo self::$linktag.'
    ';//self::$linktag is the page parsing location Path value, will be used frequently.
  6. //}
  7. }
  8. //Will be executed when accessing "http://bbs.it-home.org/testpk/"
  9. public static function index(){
  10. echo 'test' ;
  11. }
  12. //When accessing "http://bbs.it-home.org/testpk/blank", it will execute or write "http://bbs.it-home.org/testpk/index/blank" normally "index/" can be omitted
  13. public static function blank(){}
  14. }
  15. ?>
Copy code

class.rewrite.php; code show as below:

  1. class Rewrite{
  2. public static $debug = false;//Whether to turn on debugging
  3. public static $time_pass = 0;//Get the overall execution time of the module file
  4. public static $version = 2.2;
  5. public static $pretag = 'Rw_'; //Name prefix of module file class
  6. public static $linktag = 'index'; //Page link tag, used to mark which link is parsed, and can be used to control various menu effects and link access rights
  7. protected static $time_start = 0;
  8. protected static $time_end = 0;
  9. protected static $physical_path = '';//The physical path of the module file
  10. protected static $website_path = '';//The module file’s physical path Site path, because it is possible to enlarge the site to a subdirectory of the site, such as: http://bbs.it-home.org/site/mysite
  11. protected static $ob_contents = '';
  12. protected static $uid = 0;// In conjunction with personal homepage access methods such as http://bbs.it-home.org/423/, access http://bbs.it-home.org/profile?uid=423
  13. //Allowed system functions such as $allow_sys_fun =array('phpinfo') then the system will allow the link to access the phpinfo content. When http://bbs.it-home.org/phpinfo or http://bbs.it-home.org/...... ./phpinfo will directly execute the phpinfo function without the need for the phpinfo.php module file
  14. private static $allow_sys_fun = array();
  15. private static function __get_microtime(){
  16. list($usec, $sec) = explode(" ",microtime());
  17. return ((float)$usec + (float)$sec);
  18. }
  19. //Set debugging Rewrite::__debug(true);
  20. public static function __debug($d = true){
  21. static::$debug = $d;
  22. }
  23. //Configuration path and allow function
  24. public static function __config($website_path = '',$physical_path = '',$allow_sys_fun = array()){
  25. self:: $physical_path = $physical_path;
  26. self::$website_path = $website_path;
  27. self::$allow_sys_fun = $allow_sys_fun;
  28. }
  29. //Debug function
  30. public static function __msg($str){
  31. if(static::$ debug){
  32. echo "n
    n".print_r($str,true)."n
    n";
  33. }
  34. }
  35. //Parsing start time
  36. public static function __start(){
  37. self ::$time_start = self::__get_microtime();
  38. }
  39. //Parse end time
  40. public static function __end($re = false){
  41. self::$time_end = self::__get_microtime();
  42. self:: $time_pass = round((self::$time_end - self::$time_start),6) * 1000;
  43. if($re){
  44. return self::$time_pass;
  45. }else{
  46. self::__msg(' PASS_TIME: '.self::$time_pass.' ms');
  47. }
  48. }
  49. //Internal cross-module url parsing call, such as executing Rwrite::__parseurl('/test2/show' in the test1.php module page ) This sentence will call the show method in the test2.php module page (the method of the Rw_test2 class)
  50. public static function __parseurl($url = '',$fun = '',$data = NULL){
  51. if(! empty($url)&&!empty($fun)){
  52. $p = static::$physical_path;
  53. if(file_exists($p.$url) || file_exists($p.$url.'.php') ){
  54. $part = strtolower(basename( $p.$url , '.php' ));
  55. static::$linktag = $part.'/'.$fun;
  56. $fname = static::$pretag. $part;
  57. if(class_exists($fname, false)){
  58. if(method_exists($fname,$fun)){
  59. return $fname::$fun($data);
  60. }
  61. }else{
  62. include( $p.$url );
  63. if( class_exists($fname, false) && method_exists($fname,$fun)){
  64. return $fname::$fun($data);
  65. }
  66. }
  67. }
  68. }
  69. }
  70. //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
  71. public static function __parse($Url = ''){
  72. self::__start();
  73. $p = static::$physical_path;
  74. $w = static::$website_path;
  75. $req_execute = false;
  76. $url_p = empty($Url) ? $_SERVER['REQUEST_URI' ] : $Url;
  77. $local = parse_url($w);
  78. $req = parse_url($url_p);
  79. $req_path = preg_replace('|[^w/.]|','',$req['path ']);
  80. $req_para = empty($Url) ? strstr($_SERVER['SERVER_NAME'],'.',true) : 'www';
  81. if(empty($Url) && substr_count($_SERVER[' SERVER_NAME'],'.') == 2 && $req_para != 'www'){
  82. self::__goto($req_para,preg_replace('|^'.$local['path'].'|'," ",$req_path));
  83. return ;
  84. }else{
  85. $req_path_arr = empty($req_path)?array():preg_split("|[/]+|",preg_replace('|^'.$local[' path'].'|',"",$req_path));
  86. $req_fun = array_pop($req_path_arr);
  87. if(substr($req_fun,0,2)=='__'){
  88. $req_fun = substr ($req_fun,2);
  89. }
  90. $req_path_rearr = array_filter($req_path_arr);
  91. self::__msg($req_path_rearr);
  92. $req_temp = implode('/',$req_path_rearr);
  93. $fname = $req_temp. '/'.$req_fun;
  94. if(!empty($req_fun)&&in_array($req_fun,static::$allow_sys_fun)){
  95. $req_fun();
  96. }else{
  97. if(!empty($req_fun)&&file_exists( $p.$fname.'.php') ){
  98. include( $p.$fname.'.php' );
  99. }else{
  100. $fname = empty($req_temp) ? 'index' : $req_temp;
  101. if(file_exists($p.$fname.'.php') ){
  102. include( $p.$fname.'.php' );
  103. }else{
  104. $fname = $req_temp.'/index';
  105. if (file_exists($p.$fname.'.php')){
  106. include( $p.$fname.'.php' );
  107. }else{
  108. //This place directs the special link to "personal homepage" to "profile/", you can modify it yourself
  109. //For example: www.xxx.com/12/ will mean www.xxx.com/ profile/?uid=12 or www.xxx.com/profile?uid=12
  110. $uid = is_numeric($req_temp) ? $req_temp : strstr($req_temp, '/', true);
  111. $ufun = is_numeric($ req_temp) ? 'index' : strstr($req_temp, '/');
  112. if(is_numeric($uid)){
  113. self::$uid = $uid;
  114. if(!isset($_GET['uid'] )) $_GET['uid'] = $uid;
  115. $fname = 'profile/'.$ufun;
  116. if(file_exists($p.$fname.'.php')){
  117. include( $p.$ fname.'.php' );
  118. }else{
  119. header("location:".$w);
  120. exit();
  121. }
  122. }else if(file_exists($p.'index.php')){
  123. $fname = 'index';
  124. include( $p.'index.php' );
  125. }else{
  126. header("location:".$w);
  127. exit();
  128. }
  129. }
  130. }
  131. }
  132. $ev_fname = strrpos($fname,'/')===false ? $fname : substr($fname,strrpos($fname,'/')+1);
  133. $ev_fname = static::$pretag.$ev_fname ;
  134. if( class_exists($ev_fname, false) && method_exists($ev_fname,$req_fun)){
  135. static::$linktag = $req_fun=='index' ? $fname.'/' : $fname.'/' .$req_fun;
  136. if($req_fun != 'init' && method_exists($ev_fname,'init')){
  137. $ev_fname::init();
  138. }
  139. $ev_fname::$req_fun();
  140. }else if( class_exists($ev_fname, false) && method_exists($ev_fname,'index') ){
  141. static::$linktag = $fname.'/';
  142. if(method_exists($ev_fname,'init')){
  143. $ev_fname::init();
  144. }
  145. $ev_fname::index();
  146. }else if( $fname != 'index' && class_exists(static::$pretag.'index', false) && method_exists(static ::$pretag.'index','index') ){
  147. $ev_fname = static::$pretag.'index';
  148. static::$linktag = 'index/';
  149. if(method_exists($ev_fname,' init')){
  150. $ev_fname::init();
  151. }
  152. $ev_fname::index();
  153. }else{
  154. self::__msg('Function Not Exist!');
  155. }
  156. }
  157. }
  158. self::__end();
  159. }
  160. //Here is the analysis of user-defined links (using the analysis value stored in the database) such as: xiaoming.baidu.com
  161. //The xiaoming tag in the database points to a person's blog. When you get to www.baidu.com/blog?uid=12 or www.baidu.com/blog?uname=xiaoming (this depends on how you design the database)
  162. public static function __goto($para = '',$path = ' '){
  163. $w = static::$website_path;
  164. if(empty($para)){
  165. exit('Unknown link, parsing failed, cannot be accessed');
  166. }
  167. if(class_exists('Parseurl')) {
  168. $prs = Parseurl::selectone(array('tag','=',$para));
  169. self::__msg($prs);
  170. if(!empty($prs)){
  171. $parastr = $prs['tag'];
  172. $output = array();
  173. $_GET[$prs['idtag']] = $prs['id'];
  174. parse_str($prs['parastr'], $output );
  175. $_GET = array_merge($_GET,$output);
  176. $path = $prs['type'].'/'.preg_replace('|^/'.$prs['type'].'|' ,'',$path);
  177. self::__msg($path);
  178. header('location:'.$w.$path.'?'.http_build_query($_GET));
  179. exit();
  180. } else{
  181. header("location:".$w);
  182. exit();
  183. }
  184. }else{
  185. header("location:".$w);
  186. exit();
  187. }
  188. }
  189. }
  190. ? >
Copy code


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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.