PHP URL Routing Starter Example _php tutorial

Source: Internet
Author: User
first, what is the routing mechanism of PHP

1, the routing mechanism is to extract a particular form of the URL structure of the system corresponding parameters. For example, such as: HTTP://MAIN.TEST.COM/ARTICLE/1,/ARTICLE/1, _m=article&id=1.

2, and then the corresponding parameters of the URL into a specific form of the URL structure, is the reverse process of the above process.

Second, the URL routing method of PHP

Overall: Get path information, process path information

URL Routing method:

The first is the way to map through the URL parameters, typically two parameters, representing the Controller class and methods such as Index.php?c=index&m=index map to the index controller's index method.

The second, is through the Url-rewrite way, the advantage is that can be implemented to non-PHP end of the other suffixes to map, of course, through rewrite can also achieve the first way, but pure use of rewrite is also more common, generally need to configure Apache or Nginx

Rewrite rules

Copy the Code code as follows:

Rewriteengine on
Rewritebase/
Rewriterule ^index\.php$-[L]
Rewritecond%{request_filename}!-f
Rewritecond%{request_filename}!-d
Rewriterule. /index.php [L]


The third, is through the pathinfo way, so-called pathinfo, is shaped like such a URL. Xxx.com/index.php/c/index/aa/cc,apache in processing this URL will be index.php after the input to the environment variable $_server[' path_info ', it equals/c/index/aa/ Cc. Then our router can parse this string to analyze it, the latter part into the parameters where, depending on the framework of different and different.

A City simple PHP routing implementation

3.1 Modify htaccess file

Write the server Apache or IIS rewrite file, import the URL structure into the specified file such as: index.php.

The

Open rewrite:htaccess file is a configuration file in the Apache server that is responsible for the configuration of the Web page under the relevant directory. Enable. htaccess, you need to modify apache/conf/httpd.conf, enable allowoverride, and use allowoverride to limit the usage of specific commands.

copy code code is as follows:

Options followsymlinks
allowoverride None

changed to
copy code code as follows:

Options followsymlinks
allowoverride all


Then I wrote this rewrite:

copy code code is as follows:
Rewriteengine on #rewriteengine为重写引擎开关on为开启off为关闭
#RewriteCond!^ (index.php\.php|images|robots\.txt)
Rewriterule ([A-za-z]{1,})-([0-9]{1,}). html$ sharexie/test.php?action=$1&id=$2
# ([A-za-z]{1,})-([0-9]{1,} ). html$ is the rule, and sharexie/test.php?action=$1&id=$2 is the format to replace, which represents the value that the first parenthesis matches, and that is the second one. The code above

is to import the URL structure into sharexie/test.php. Save these as. htaccess files in the root directory of the Web site.

test.php

Copy the Code code as follows:
Echo ' Your action is: '. $_get[' action '];
Echo '
';
Echo ' Your ID is: '. $_get[' id '];
?>
OK, now we're typing in the browser:

127.0.0.1/view-12.html

The output is:

Your action is: view

Your ID is: 12

1, explain the Rewriterule:

Rewriterule is a rewrite rule that supports regular expressions, the above ([0-9]{1,}) refers to numbers, $ is the end flag, and the description is the end of the number!

2. Rewriterule Configuration Parameters

1) R Force external redirection
2) F disable URL, return 403HTTP status code.
3) G force URL is gone, return 410HTTP status code.
4) P forces the use of proxy forwarding.
5) L indicates that the current rule is the last rule, which stops the rewrite of the rule after parsing.
6) N re-run the rewrite process starting with the first rule.
7) C is associated with the next rule 8) T=mime-type (Force MIME type) enforces MIME type
9) NS is only used for internal sub-requests
NC is case insensitive
One) QSA Append request string
NE not output escape special character \%3d$1 equivalent to =$1

Example:

1, will XIANGLC will be set to INDEX.PHP?C=MYUSER&M=ITIME&DOMAIN=XIANGLC
Copy the Code code 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]
Copy the Code code 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 to parse the rules, match and convert URLs.

Move all the links to index.php, route distribution in index.php, and assign classes and methods to the functions in the corresponding class file. Use $_server[' Request_uri '] to remove the part of the URL from the www.xx.com/, respectively, according to the relevant rules are class and Mothod and the value of the parameter key=>value. Finally include the class file, which executes the function. Examples are as follows:
Copy CodeThe 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 invoke 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");
}
?>

http://www.bkjia.com/PHPjc/759966.html www.bkjia.com true http://www.bkjia.com/PHPjc/759966.html techarticle first, what is the PHP routing mechanism 1, the routing mechanism is to take a particular form of the URL structure to extract the corresponding parameters of the system. For example, such as: HTTP://MAIN.TEST.COM/ARTICLE/1 ...

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