thinkphp路由规则使用示例详解和伪静态功能实现(apache重写)_php实例
//thinkphp 路由定义规则
$route = array(
'news/:action/:year\d/:month/:day'=>'news/read?year=:2&month=:3&day=:4',
'news/:action^delete|update|insert/:year\d/:month/:day'=>array( 'news/read?extra=:2&status=1','year=:2&month=:3&day=:4'),
);
$url = 'http://www.test.com/index.php/news/read/2012/2/21/extraparam/test.html';
//后缀名
$extension = 'html';
//可知: $_SERVER['PATH_INFO'] = 'news/read/2012/2/21/extraparam/test.html';
$regx = 'news/read/2012/2/21/extraparam/test.html';
//循环匹配路由规则
foreach($route as $key=>$value){
//如果匹配成功,则不继续匹配
if(parseUrlRule($key,$value,$regx,$extension))
break;
}
//运行结果: 打印$_GET
//Array
// (
// [actionName] => read
// [moduleName] => news
// [extra] => 2012
// [status] => 1
// [extraparam] => test
// [year] => 2012
// [month] => 2
// [day] => 21
// [finalUrl] => news/read?extra=2012&status=1&extraparam=test&year=2012&month=2&day=21
// )
// [Finished in 0.6s]
//相当于访问: http://www.test.com/news/read?extra=2012&status=1&extraparam=test&year=2012&month=2&day=21
//在部署时会把index.php隐藏,开启apache的重写模块
//重写规则 : RewriteRule ^(.+)$ /index.php/$1
//开启后,apache会自动把 http:/www.test.com/news/read/2012/2/21/extraparam/test.html转换为 http:/www.test.com/index.php/news/read/2012/2/21/extraparam/test.html
/**
* @$rule string 路由规则
* @$route string 规则映射的新地址
* @$regx string 地址栏pathinfo字符串
* @$extension stirng 伪静态拓展名
* return bool
*/
function parseUrlRule($rule,$route,$regx,$extension=null){
//去掉后缀名
!is_null($extension) && $regx = str_replace('.'.$extension,'',$regx);
//把路由规则和地址,分割到数组中,然后逐项匹配
$ruleArr = explode('/',$rule);
$regxArr = explode('/',$regx);
//$route以数组的格式传递,则取第一个
$url = is_array($route) ? $route[0] : $route;
$match =true;
//匹配检测
foreach($ruleArr as $key=>$value){
if(strpos($value,':')===0){
if(substr($value,-2)=='\\d' && !is_numeric($regxArr[$key])){
$match = false;
break;
}elseif(strpos($value,'^')){
$stripArr = explode('|',trim(strstr($value,'^'),'^'));
if(in_array($regxArr[$key],$stripArr)){
$match = false;
break;
}
}
//静态项不区分大小写
}elseif(strcasecmp($value, $regxArr[$key])!==0) {
$match = false;
break;
}
}
//匹配成功
if($match){
//把动态变量写入到数组$matches 中,同时去除静态匹配项
foreach($ruleArr as $key=>$value){
if(strpos($value,':')===0){
//获取动态变量,作为数组下标
if(substr($value,-2,1)=='\\')
$matchKey = substr($value,1,-2);
elseif($pos=strpos($value,'^'))
$matchKey =substr($value,1,$pos-1);
else
$matchKey = substr($value,1);
$matches[$matchKey] = array_shift($regxArr);
}else
array_shift($regxArr); //去除静态匹配项
}
//获取数组中的值,目的是配合子模式进行替换
$values = array_values($matches);
//正则匹配替换,正则需要用'e'作为修饰符
$url = preg_replace('/:(\d+)/e','$values[\\1-1]',$url);
//解析url 格式: 分组/模块/操作?key1=value1&key2=value2
if(strpos($url,'?')!==false){
// 分组/模块/操作?key1=value1&key2=value2
$arr = parse_url($url);
$paths = explode('/',$arr['path']);
parse_str($arr['query'],$queryArr);
}elseif(strpos($url,'/')!==false) //分组/模块/操作)
$paths = explode('/',$url);
else // key1=value1&key2=value2
parse_str($url,$queryArr);
//获取 分组 模块 操作
if(!empty($paths)){
$var['actionName'] = array_pop($paths);
$var['moduleName'] = array_pop($paths);
if(!empty($paths)){
$groupList = 'Home,Admin';
$temp = array_pop($paths);
if(in_array($temp,explode(',',$groupList)))
$var['groupName'] = $temp;
}
}
//合并的到GET数组中,方便全局调用
$_GET = array_merge($_GET,$var);
//合并参数
if(isset($queryArr))
$_GET = array_merge($_GET,$queryArr);
//匹配url中剩余的参数
preg_replace('/(\w+)\/([^,\/]+)/e','$tempArr[\'\\1\']=\'\\2\'',implode('/',$regxArr));
if(!empty($tempArr))
$_GET = array_merge($_GET,$tempArr);
//route是数组的话
if(is_array($route)){
$route[1]=preg_replace('/:(\d+)/e','$values[\\1-1]',$route[1]);
parse_str($route[1],$var);
$_GET = array_merge($_GET,$var);
strpos($url,'?')!==false ? $der ='&' : $der='?';
//最终写入到$_GET中的参数,包括三个部分
//1.地址栏剩余参数
//2.路由地址中的参数
//3.$route是数组时的第二个参数
if(!empty($tempArr))
$var = array_merge($tempArr,$var);
$url .=$der.http_build_query($var);
}
$_GET['finalUrl'] = $url;
//保证$_REQUEST 也能访问
$_REQUEST = array_merge($_REQUEST,$_GET);
//结果
print_r($_GET);
return true;
}
return $match;
}
//以下是正则路由代码:
$rule = '/news\/read\/(\d+)\/(\d+)\/(\d+)/';
$route ='news/read?year=:1&month=:2&day=:3';
$regx = 'news/read/2012/2/21/extraparam/test.html';
$extension = 'html';
parseUrlRuleRegx($rule,$route,$regx,$extension);
/**
* @$rule string 路由规则
* @$route string 规则映射的新地址
* @$regx string 地址栏pathinfo字符串
* @$extension stirng 伪静态拓展名
* return bool
*/
function parseUrlRuleRegx($rule,$route,$regx,$extension=null){
!is_null($extension) && $regx = str_replace('.'.$extension,'',$regx);
$url = is_array($route) ? $route[0] : $route;
if(preg_match($rule,$regx,$matches)){
$url = preg_replace('/:(\d+)/e','$matches[\\1]',$url);
}else
return false;
//解析url 格式: 分组/模块/操作?key1=value1&key2=value2
if(strpos($url,'?')!==false){
// 分组/模块/操作?key1=value1&key2=value2
$arr = parse_url($url);
$paths = explode('/',$arr['path']);
parse_str($arr['query'],$queryArr);
}elseif(strpos($url,'/')!==false) //分组/模块/操作)
$paths = explode('/',$url);
else // key1=value1&key2=value2
parse_str($url,$queryArr);
//获取 分组 模块 操作
if(!empty($paths)){
$var['actionName'] = array_pop($paths);
$var['moduleName'] = array_pop($paths);
if(!empty($paths)){
$groupList = 'Home,Admin';
$temp = array_pop($paths);
if(in_array($temp,explode(',',$groupList)))
$var['groupName'] = $temp;
}
}
//合并的到GET数组中,方便全局调用
$_GET = array_merge($_GET,$var);
if(isset($queryArr))
$_GET = array_merge($_GET,$queryArr);
//匹配剩余的参数
$regx = str_replace($matches[0],'',$regx);
preg_replace('/(\w+)\/([^,\/]+)/e','$tempArr[\'\\1\']=\'\\2\'',$regx);
if(!empty($tempArr)){
$_GET = array_merge($_GET,$tempArr);
strpos($url,'?')!==false ? $der='&':$der='?';
$url .=$der.http_build_query($tempArr);
}
if(is_array($route)){
$route[1] = preg_replace('/:(\d+)/e','$matches[\\1]',$route[1]);
parse_str($route[1],$var);
if(!empty($var)){
!empty($queryArr) && $var =array_merge($queryArr,$var);
$_GET= array_merge($_GET,$var);
}
strpos($url,'?')!==false ? $der='&':$der='?';
$url .=$der.http_build_query($var);
}
$_GET['finalUrl'] = $url;
print_r($_GET);
$_REQUEST = array_merge($_GET,$_REQUEST);
return true;
}
//运行结果:
//Array
// (
// [actionName] => read
// [moduleName] => news
// [year] => 2012
// [month] => 2
// [day] => 21
// [extraparam] => test
// [finalUrl] => news/read?year=2012&month=2&day=21&extraparam=test
// )
// [Finished in 0.1s]

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


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

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

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.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment