php url路由入门实例_php实例
一、什么是php的路由机制
1、路由机制就是把某一个特定形式的URL结构中提炼出来系统对应的参数。举个例子,如:http://main.test.com/article/1 其中:/article/1 -> ?_m=article&id=1。
2、然后将拥有对应参数的URL转换成特定形式的URL结构,是上面的过程的逆向过程。
二、PHP的URL路由方式
总体来说就是:获取路径信息->处理路径信息
URL路由方式:
第一种是通过url参数进行映射的方式,一般是两个参数,分别代表控制器类和方法比如index.php?c=index&m=index映射到的是index控制器的index方法。
第二种,是通过url-rewrite的方式,这样的好处是可以实现对非php结尾的其他后缀进行映射,当然通过rewrite也可以实现第一种方式,不过纯使用rewrite的也比较常见,一般需要配置apache或者nginx的
rewrite规则
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
第三种,就是通过pathinfo的方式,所谓的pathinfo,就是形如这样的url。xxx.com/index.php/c/index/aa/cc,apache在处理这个url的时候会把index.php后面的部分输入到环境变量$_SERVER['PATH_INFO'],它等于/c/index/aa/cc。然后我们的路由器再通过解析这个串进行分析就可以了,后面的部分放入到参数什么地方的,就依据各个框架不同而不同了。
三、 一个简单的PHP路由实现
3.1 修改htaccess文件
编写服务器apache或IIS自带的rewrite文件,将URL结构导入指定文件比如:index.php。
开启rewrite:htaccess文件是Apache服务器中的一个配置文件,它负责相关目录下的网页配置。启用.htaccess,需要修改apache/conf/httpd.conf,启用AllowOverride,并可以用AllowOverride限制特定命令的使用。
Options FollowSymLinks
AllowOverride None
改为
Options FollowSymLinks
AllowOverride All
然后我写了这样的rewrite:
RewriteEngine on #rewriteengine为重写引擎开关on为开启off为关闭
#RewriteCond $1 !^(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$是规则,sharexie/test.php?action=$1&id=$2是要替换的格式,$1代表第一个括号匹配的值,$2代表第二个。
上面的代码就是将URL结构导入sharexie/test.php中。把这些保存为.htaccess文件放在网站的根目录就行了。
test.php
echo '你的Action是:' . $_GET['action'];
echo '
';
echo '你的ID是:' . $_GET['id'];
?>
好了,我们现在在浏览器中输入:
127.0.0.1/view-12.html
输出的是:
你的Action是:view
你的ID是:12
1、讲解一下RewriteRule:
RewriteRule是重写规则,支持正则表达式的,上面的([0-9]{1,})是指由数字组成的,$是结束标志,说明是以数字结束!
2、RewriteRule配置参数
1) R 强制外部重定向
2) F 禁用URL,返回403HTTP状态码。
3) G 强制URL为GONE,返回410HTTP状态码。
4) P 强制使用代理转发。
5) L 表明当前规则是最后一条规则,停止分析以后规则的重写。
6) N 重新从第一条规则开始运行重写过程。
7) C 与下一条规则关联8) T=MIME-type(force MIME type) 强制MIME类型
9) NS 只用于不是内部子请求
10) NC 不区分大小写
11) QSA 追加请求字符串
12) NE 不在输出转义特殊字符 \%3d$1 等价于 =$1
举例:
1、将xianglc将定到 index.php?c=myuser&m=itime&domain=xianglc
RewriteRule ^([a-zA-Z0-9]){6,20}/?$ index.php?c=myuser&m=itime&domain=$0 [L]
2、#RewriteRule ^/index.html$ /1.php [L]
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 一个路由解析器,用来解析规则,匹配和转换URL。
先将所有的链接转到index.php中,在index.php中进行路由分发,按照类和方法分配到相应的类文件中的函数上去。用$_SERVER['REQUEST_URI']取出URL中的www.xx.com/后面的部分,按照相关规则分别区分为class和mothod以及参数key=>value的值。最后include该类文件,执行其中的函数。实例如下:
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 $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('参数错误');
} else {
for ($i = 2; $i $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("要调用的方法不存在");
} else {
if (is_callable(array($obj_module, $method_name))) {
$obj_module -> $method_name($module_name, $arr_url['parms']);
$obj_module -> printResult();
}
}
} else {
die("定义的模块不存在");
}
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
