Phpurl entry-level instance

Source: Internet
Author: User
This article mainly introduces the phpurl entry-level instance to parse the implementation details of url routing. For more information, see 1. what is the php routing mechanism?

1. the routing mechanism is to extract the system parameters from a specific URL structure. For example: http://main.test.com/article/1 Where:/article/1->? _ M = article & id = 1.

2. convert the URL with corresponding parameters into a specific URL structure, which is the inverse process of the above process.

II. php url routing

In general, it is: get path information-> process path information

URL routing method:

The first method is to map through url parameters. Generally, there are two parameters, representing the controller class and method, such as index. php? C = index & m = the index method mapped to the index controller.

The second method is through url-rewrite. the advantage is that it can map other suffixes not ending with php. of course, the first method can be implemented through rewrite, however, the use of rewrite is also common. generally, apache or nginx needs to be configured.

Rewrite rules

The code is as follows:

RewriteEngine On
RewriteBase/
RewriteRule ^ index \. php $-[L]
RewriteCond % {REQUEST_FILENAME }! -F
RewriteCond % {REQUEST_FILENAME }! -D
RewriteRule./index. php [L]


The third method is pathinfo. The so-called pathinfo is a url like this. Bytes. Then our vro can analyze it by parsing this string. the later part is placed in the parameter, which is different from each frame.

3. a simple PHP route implementation

3.1 modify the htaccess file

Write the rewrite file that comes with apache or IIS on the server, and import the URL structure to the specified file, for example, index. php.

Enable rewrite: the htaccess file is a configuration file on the Apache server. it is responsible for the webpage configuration under the relevant directory. To enable. htaccess, you need to modify apache/conf/httpd. conf, enable AllowOverride, and use AllowOverride to restrict the use of specific commands.

The code is as follows:

Options FollowSymLinks
AllowOverride None

Change
The code is as follows:

Options FollowSymLinks
AllowOverride All


Then I wrote such a rewrite:

The code is as follows:
RewriteEngine on # rewriteengine is the rewrite engine switch on is to turn off
# RewriteCond $1! ^ (Index. php \. php | images | robots \. txt)
RewriteRule (‑a-za-z‑00001, 00000000-(‑0-9000000001, 00000000.html $ sharexie/test. php? Action = $1 & id = $2
Rule ([a-za-z1_00001, 00000000-(%0-9000000001, 00000000.html $ is the rule, sharexie/test. php? Action = $1 & id = $2 is the format to be replaced. $1 indicates the matching value of the first parenthesis, and $2 indicates the second.

The above code imports the URL structure into sharexie/test. php. Save these files as. htaccess files in the root directory of the website.

Test. php

The code is as follows:
Echo 'your Action is: '. $ _ GET ['action'];
Echo'
';
Echo 'Your ID is: '. $ _ GET ['id'];
?>
Now, in the browser, enter:

127.0.0.1/view-12.html

The output is:

Your Action is: view

Your ID is: 12

1. RewriteRule:

RewriteRule is a rewrite rule that supports regular expressions. the above ([0-9] {1,}) is composed of numbers. $ is the ending sign, indicating that it ends with a number!

2. RewriteRule configuration parameters

1) R forces external redirection
2) F disables the URL and returns the 403HTTP status code.
3) if G forces the URL to be GONE, the response HTTP status code is returned.
4) P enforces proxy forwarding.
5) L indicates that the current rule is the last rule, and the rule is overwritten after analysis is stopped.
6) N re-run the rewrite process from the first rule.
7) C associated with the next rule 8) T = MIME-type (force MIME type) forced MIME type
9) NS is only used for non-internal subrequests
10) the NC is case insensitive.
11) QSA append request string
12) NE does not output escape special characters \ % 3d $1 is equivalent to = $1

Example:

1. set xianglc to index. php? C = myuser & m = itime & domain = xianglc
The code is as follows:
RewriteRule ^ ([a-zA-Z0-9]) {6, 20 }/? $ Index. php? C = myuser & m = itime & domain = $0 [L]
2. # RewriteRule ^/index.html $/1.php [L]
The 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 (.*?) $/1.php? $7 & I = $1 & j = $2 & k = $3 & l = $4 & m = $5 & n = $6 [QSA, L, NC]


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

First, transfer all links to index. php, distribute routes in index. php, and distribute the links to functions in the corresponding class file according to the class and method. Use $ _ SERVER ['request _ URI '] to retrieve the values of www.xx.com/and later in the URL. according to the relevant rules, the values are classified as classand mothodand the value of key=> value. Finally, include the class file and execute the function. Example:
The code is as follows:
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 \ index. php
$ _ 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. '. class. php ';
$ 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 ");
}
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.