SoFunction
Updated on 2025-04-04

PHP url routing example

1. What is the routing mechanism of php

1. The routing mechanism is to extract the corresponding parameters of the system from a specific form of URL structure. For example, for example: /article/1  where: /article/1  -> ?_m=article&id=1.

2. Then converting the URL with the corresponding parameters into a specific form of URL structure is the reverse process of the above process.

2. PHP URL routing method

Generally speaking, it is: obtain path information->process path information

URL routing method:

The first method is to map through url parameters, which generally have two parameters, representing the controller class and method, such as ?c=index&m=index mapped to the index controller's index method.

The second method is through url-rewrite. This advantage is that it can map other suffixes that are not ended by php. Of course, the first method can also be implemented through rewrite. However, purely using rewrite is also common. Generally, it is necessary to configure apache or nginx.

Rewrite rules

Copy the codeThe code is as follows:

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


The third type is through pathinfo. The so-called pathinfo is a URL that looks like this. //c/index/aa/cc. When apache processes this url, it will input the subsequent part to the environment variable $_SERVER['PATH_INFO'], which is equal to /c/index/aa/cc. Then our router can analyze this string and analyze it. The subsequent part is placed in the parameters and different parts depending on the framework.

3. A simple PHP routing implementation

3.1 Modify htaccess file

Write the rewrite file that comes with the server apache or IIS, and import the URL structure into the specified file, for example:.

Enable rewrite: htaccess file is a configuration file in the Apache server, which is responsible for the web page configuration in the relevant directories. To enable .htaccess, you need to modify apache/conf/, enable AllowOverride, and you can use AllowOverride to restrict the use of specific commands.

Copy the codeThe code is as follows:

<Directory /> 
Options FollowSymLinks 
AllowOverride None 
</Directory> 

Change to
Copy the codeThe code is as follows:

<Directory /> 
Options FollowSymLinks 
AllowOverride All 
</Directory> 


Then I wrote a rewrite like this:

Copy the codeThe code is as follows:

RewriteEngine on #rewriteengine is the rewrite engine switch on is on to turn off and off
#RewriteCond $1 !^(\.php|images|robots\.txt) 
RewriteRule ([a-zA-Z]{1,})-([0-9]{1,}).html$ sharexie/?action=$1&id=$2 

#([a-zA-Z]{1,})-([0-9]{1,}).html$ is the rule, sharexie/?action=$1&id=$2 is the format to be replaced, $1 represents the value matched by the first bracket, and $2 represents the second.

The above code is to import the URL structure into sharexie/. Save these as .htaccess files and put them in the root directory of the website.



Copy the codeThe code is as follows:

<?php 
echo 'Your Action is:' . $_GET['action'];
echo '<br/>'; 
echo 'Your ID is:' . $_GET['id'];
?> 

OK, let's enter in the browser now:

127.0.0.1/

The output is:

Your Action is: view

Your ID is: 12

1. Explain RewriteRule:

RewriteRule is a rewrite rule and supports regular expressions. The above ([0-9]{1,}) refers to a number, and $ is the end flag, indicating that it ends with a number!

2. RewriteRule configuration parameters

1) R Force external redirection
2) F Disable URL and return 403HTTP status code.
3) G Force URL to be GONE, and return 410HTTP status code.
4) P Force the use of proxy forwarding.
5) L indicates that the current rule is the last rule, and the rewriting of the subsequent rules is stopped.
6) N Start the rewrite process again from the first rule.
7) C is associated with the next rule 8) T=MIME-type(force MIME type) Force MIME type
9) NS  is only used for not internal subrequests
10) NC is case-insensitive
11) QSA append request string
12) NE does not escape special characters in output   \%3d$1  is equivalent to =$1

For example:

1. Set xianglc to ?c=myuser&m=time&domain=xianglc

Copy the codeThe code is as follows:

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

2、#RewriteRule ^/$ / [L]           
Copy the codeThe code is as follows:

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


3.2 A routing parser used to parse rules, match and convert URLs.

First, transfer all links to the middle, route and distribute them in the middle, and assign them to the functions in the corresponding class file according to the class and methods. Use $_SERVER['REQUEST_URI'] to remove the /after part in the URL, and distinguish it into class and mothod and the value of parameter key=>value according to relevant rules. Finally include the file of this class and execute the functions in it. Examples are as follows:

Copy the codeThe code is as follows:

<?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);    //==>\router\ 
$_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('parameter error');
   } 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.'.'; 
   $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("The method to be called does not exist");
       } else { 
           if (is_callable(array($obj_module, $method_name))) { 
               $obj_module -> $method_name($module_name, $arr_url['parms']);               
               $obj_module -> printResult(); 
           } 
       }       
   } else { 
die("The defined module does not exist");
   } 
?>