本节内容:
php url路由功能
1,符合规则定义的伪静态访问路径解析
例如,"test.php/user/lists/normal/id/2.html" 可解析为
例如,"test.php/users/lists.html" 可解析为
2,不符合规则定义的伪静态路径解析
action,control 不符合规则
例如,"test.php/users/lists/all/id1/1.html" 报错
试图访问不存在的页面
不符合匹配模式
例如,"test.php/user/lists/all/id1/1.html" 可解析为
control = user,action = lists,filter = all,order = '',curPage = 1
可取得不符合匹配模式项目的默认值。
例子:
<?php
/**
* php url路由功能实例
* by www.jb200.com
*/
// url 路由规则定义
$urlRule = array(
'user' => array(// control
'lists' => array( // action
//'名称'=> '默认值,值模式匹配'
'filter' => 'all,^(all|normal|admin)$',
'order'=> ',^-?[a-zA-Z_]+$',
'curPage' => '1,^[0-9]+$',
),
),
);
function parseUrl(){
$queryString = array();
$GLOBALS['control'] = 'index';
$GLOBALS['action'] = 'index';
if (isset($_SERVER['PATH_INFO'])){
//获取 pathinfo
$aPathInfo = explode('/', substr($_SERVER['PATH_INFO'], 1, strrpos($_SERVER['PATH_INFO'], '.')-1));
// 获取 control
$GLOBALS['control'] = $aPathInfo[0];
array_shift($aPathInfo);
// 获取 action
$GLOBALS['action'] = (isset($aPathInfo[0]) ? $aPathInfo[0] : 'index');
array_shift($aPathInfo);
// 获取 入口文件名
$GLOBALS['PHP_SELF'] = str_replace($_SERVER['PATH_INFO'], '', $_SERVER['PHP_SELF']);
$queryString = $aPathInfo;
}
parseQueryString($queryString);
}
function parseQueryString(array$aQueryString){
$queryString = array();
// control 与 action 为默认值时
if ($GLOBALS['control'] == 'index' && $GLOBALS['action'] == 'index'){
$GLOBALS['queryString'] = $queryString;
return true;
}
global $urlRule;
if (isset($urlRule[$GLOBALS['control']][$GLOBALS['action']])){
$aActionRule = &$urlRule[$GLOBALS['control']][$GLOBALS['action']];
foreach ($aActionRule as $key=>$val){
// 规则值为 '' 时
if ($val == '') {
$queryString[$key] = '';
continue;
}
if (isset($aQueryString[0])){
// 取得正则表达式
$pattern = '/'.substr($val, strpos($val, ',')+1).'/';
// 模式匹配
if (preg_match($pattern, $aQueryString[0])){
// 取值
$queryString[$key] = $aQueryString[0];
// 弹出值
array_shift($aQueryString);
}else {
// 取默认值
$queryString[$key] = substr($val, 0, strpos($val, ','));
}
}else {
// 取默认值
$queryString[$key] = substr($val, 0, strpos($val, ','));
}
}
$GLOBALS['queryString'] = $queryString;
}else {
throw new Exception('试图访问不存在的页面');
}
}
parseUrl();
var_dump($GLOBALS['control']);
var_dump($GLOBALS['action']);
var_dump($GLOBALS['queryString']);
?>