如果一个页面的内容呈现,需要根据url上传递的参数来进行渲染。很多时候可能是这样子写:xxx.com/xx?c=x&m=x&t=..,而我们看到的url往往是这样子的(以新浪微游戏的咖啡恋人为例) game.weibo.com/ilovecoffee….这种URL设计看上去比前一种更好一点:)

如果我们访问一下不存在的游戏应用,例如game.weibo.com/ilovecoffee222,则会输出如下的错误提示:

PHP实现一个简单url路由功能

 

game.weibo.com后面匹配到的项,指向了某个php页面,然后根据参数获取要访问的游戏应用标识,后数据库或者缓存里查询该应用标识,如果不存在则输出错误提示,如果应用存在则加载游戏应用链接地址。

 

现在写一个php例子,假设我的ip为192.168.0.33,我加了一层名为router的路径,之后跟随的是 “/模块名/方法名/参数1的key/参数1的value/….”

类似这样的地址:

192.168.0.33/router/Hello/router/a/b/c/d/abc/index.html?id=3&url=http:………………

也就是要调用Ha这个模块中的router方法,并传入url后面的参数/a/b/c/d/index………….

 

第一步,首先要在服务器的配置上对/router/路径进行拦截

 PHP实现一个简单url路由功能

调用某个文件夹目录下的index.php页面,假定现在所有模块使用单独的文件存放于class目录下,该目录与router平级,如下图所示:

PHP实现一个简单url路由功能 

 

第二步,路由分发器的实现(index.php)

1: <!Doctype html>
   2: <html>
   3: <head>
   4: <title>路由测试~~</title>
 />
   6: </head>
   7: <body>
   8:  
   9: <?php
  10:  
);
  12:  
);
  14:  
  15:  
'DOCUMENT_ROOT'];
  17: $_FilePath = __FILE__;
'REQUEST_URI'];
  19:  
//==>\router\index.php
//==>/router/hello/router/a/b/c/d/abc/index.html?id=3&url=http:
  22:  
  23: $_AppPathArr = explode(DIRECTORY_SEPARATOR, $_AppPath);
  24:  
/**
 * http://192.168.0.33/router/hello/router/a/b/c/d/abc/index.html?id=3&url=http:
 * 
 * /hello/router/a/b/c/d/abc/index.html?id=3&url=http:
 */
  30:  
for ($i = 0; $i < count($_AppPathArr); $i++) {
  32:     $p = $_AppPathArr[$i];
if ($p) {
'/', $_UrlPath, 1);
  35:     }
  36: }
  37:  
'', $_UrlPath, 1);
  39:  
, $_UrlPath);
  41: $_AppPathArr_Count = count($_AppPathArr);
  42:  
array(
'index',
'index',
array()
  47: );
  48:  
'controller'] = $_AppPathArr[0];
'method'] = $_AppPathArr[1];
  51:  
and $_AppPathArr_Count % 2 != 0) {
'参数错误');
else {
for ($i = 2; $i < $_AppPathArr_Count; $i += 2) {
array(strtolower($_AppPathArr[$i])=>$_AppPathArr[$i + 1]);
'parms'], $arr_temp_hash);
  58:     }
  59: }
  60:  
'controller'];
'.class.php';
'method'];
  64:  
if (file_exists($module_file)) {
include $module_file;
  67:     
new $module_name();
  69:     
if (!method_exists($obj_module, $method_name)) {
);
else {
array($obj_module, $method_name))) {
'parms']);
  75:             
  76:             $obj_module -> printResult();
  77:         }
  78:     }
  79:     
else {
);
  82: }
  83:  
  84:  
  85: ?>
  86:  
  87: </body>
  88: </html>

相关文章:

  • 2021-09-17
  • 2021-10-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-19
  • 2021-07-31
猜你喜欢
  • 2022-03-08
  • 2021-12-03
  • 2021-12-07
  • 2022-12-23
  • 2022-03-06
  • 2022-02-22
  • 2022-12-23
相关资源
相似解决方案