PHP简单MVC架构

左心房为你撑大大i 提交于 2020-02-03 02:42:22

http://blog.csdn.net/haiqiao_2010/article/details/12166283

由于需要搭建一个简单的框架来进行API接口开发,所以简单的mvc框架当然是首选.最原始,最简洁的mvc框架.下面来介绍下.

        一. 项目目录结构:

app 
|-controller    存放控制器文件 
|-model        存放模型文件 
|-view        存放视图文件    

core
|-lib        存放自定义类库 
|-config    存放配置文件 
|--config.php   系统配置文件 

|--conn.php   数据库连接文件 

|--db_config.php   数据库配置文件 
|-mysql_db.php    数据库类文件 

|-runtime    缓存文件

db_caches 数据库缓存文件

logs日志文件

|-index.php    入口文件 

| -dispatcher.php

| -loader.php

| -router.php

二.项目架构

1.先介绍index.php,附源码:

 

[php] view plain copy
 
  1. <?php  
  2. include("./core/ini.php");  
  3. include("./core/config/config.php");  
  4. include("./core/global.fun.php");  
  5. include("./core/common.php");  
  6.   
  7. initializer::initialize();//加载将要用到的目录文件<span style="font-family:verdana,sans-serif; font-size:13px; line-height:19px">,即调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.</span>  
  8. $router = loader::load("router");//加载URL处理文件,对url进行解析--<span style="font-family:verdana,sans-serif; font-size:13px; line-height:19px">加载loader函数的静态函数load</span>  
  9. dispatcher::dispatch($router);//<span style="font-family:verdana,sans-serif; font-size:13px; line-height:19px">router.php文件,这个文件的作用就是映射URL,对URL进行解析.</span>根据解析到的URL参数加载相关controller及action  
  10. ?>  

 


2.初始化项目文件 ./core/ini.php 源码:

 

 

[php] view plain copy
 
  1. <?php  
  2. set_include_path(get_include_path() . PATH_SEPARATOR . "core/main");  
  3. //set_include_path — Sets the include_path configuration option  
  4. function __autoload($object){  
  5.     require_once("{$object}.php");  
  6. }  

这个文件首先设置了include_path,也就是我们如果要找包含的文件,告诉系统在这个目录下查找。其实我们定义__autoload()方法,这个方法是在PHP5增加的,就是当我们实例化一个函数的时候,如果本文件没有,就会自动去加载文件

3.加载系统配置文件./core/config.php 源码:

 

 

[php] view plain copy
 
  1. <?php  
  2.     /* 
  3.     * 设置页面编码格式 
  4.     */  
  5.     header("content-type:text/html;charset=utf-8");  
  6.     //禁用错误报告  
  7.     error_reporting(0);  
  8.     date_default_timezone_set("PRC");  
  9.     //定义常量  
  10.     define("URL_PATH","<a target="_blank" href="http://blog.csdn.net/haiqiao_2010">http://blog.csdn.net/haiqiao_2010</a>");//服务器IP  
  11.     define('IMG_PATH',"<a target="_blank" href="http://blog.csdn.net/haiqiao_2010">http://blog.csdn.net/haiqiao_2010</a>");//服务器图片目录  
  12.       
  13.     //判断日志是否开启  
  14.     defined("APP_LOG") or define("APP_LOG",true);  
  15.     if (APP_LOG) {  
  16.         $GLOBALS['log'] = new APIlog();  
  17.         set_exception_handler(array($GLOBALS['log'],'quit'));  
  18.         set_error_handler(array($GLOBALS['log'],'error_handle'));  
  19.     }  
  20.       
  21.     define('IS_CGI',substr(PHP_SAPI, 0,3)=='cgi' ? 1 : 0 );  
  22.     define('IS_WIN',strstr(PHP_OS, 'WIN') ? 1 : 0 );  
  23.     define('IS_CLI',PHP_SAPI=='cli'? 1   :   0);  
  24.     if(!defined('APP_NAME')) define('APP_NAME', basename(dirname($_SERVER['SCRIPT_FILENAME'])));  
  25.     if(!IS_CLI) {  
  26.         // 当前文件名  
  27.         if(!defined('_PHP_FILE_')) {  
  28.             if(IS_CGI) {  
  29.                 //CGI/FASTCGI模式下  
  30.                 $_temp  = explode('.php',$_SERVER["PHP_SELF"]);  
  31.                 define('_PHP_FILE_',  rtrim(str_replace($_SERVER["HTTP_HOST"],'',$_temp[0].'.php'),'/'));  
  32.             }else {  
  33.                 define('_PHP_FILE_',    rtrim($_SERVER["SCRIPT_NAME"],'/'));  
  34.             }  
  35.         }  
  36.         if(!defined('__ROOT__')) {  
  37.             // 网站URL根目录  
  38.             if( strtoupper(APP_NAME) == strtoupper(basename(dirname(_PHP_FILE_))) ) {  
  39.                 $_root = dirname(dirname(_PHP_FILE_));  
  40.             }else {  
  41.                 $_root = dirname(_PHP_FILE_);  
  42.             }  
  43.             define('__ROOT__',   (($_root=='/' || $_root=='\\')?'':$_root));  
  44.         }  
  45.       
  46.         //支持的URL模式  
  47.         define('URL_COMMON',      0);   //普通模式  
  48.         define('URL_PATHINFO',    1);   //PATHINFO模式  
  49.         define('URL_REWRITE',     2);   //REWRITE模式  
  50.         define('URL_COMPAT',      3);   // 兼容模式  
  51.     }  
  52.       
  53.       
  54.     if(!defined('APP_ROOT')) {//项目根路径  
  55.         // 网站URL根目录  
  56.         $_root = dirname(_PHP_FILE_);  
  57.         $_root = (($_root=='/' || $_root=='\\')?'':$_root);  
  58.         $_root = str_replace("/system","",$_root);  
  59.         define('APP_ROOT', $_root  );  
  60.     }  
  61.     if(!defined('APP_ROOT_PATH'))//项目绝对路径  
  62.         define('APP_ROOT_PATH', str_replace("\\","/",substr(dirname(__FILE__),0,-11)));  
  63.       
  64.     if(!defined('PAGE_SIZE'))//im:页面大小  
  65.         define('PAGE_SIZE',15);  
  66.   
  67. ?>  

 


4.加载通用的方法的文件./core/global_fun.php 源码:

[php] view plain copy
 
  1.   
[php] view plain copy
 
  1. <?php  
  2.    //header("content-type:text/html;charset=utf-8");  
  3.     /* 
  4. <span style="white-space:pre">  </span>*   过滤sql语句的关键字 
  5. <span style="white-space:pre">  </span>*/  
  6.     function strip_sql($string){  
  7. <span style="white-space:pre">  </span>   global $search_arr,$replace_arr;  
  8. <span style="white-space:pre">  </span>   return is_array($string) ? array_map('strip_sql', $string) : preg_replace($search_arr, $replace_arr, $string);  
  9.    }  
  10.   
  11.   
  12.    function new_htmlspecialchars($string){  
  13. <span style="white-space:pre">      </span>return is_array($string) ? array_map('new_htmlspecialchars', $string) : htmlspecialchars($string,ENT_QUOTES);  
  14.    }  
  15.   
  16.   
  17.    function new_addslashes($string){  
  18. <span style="white-space:pre">      </span>if(!is_array($string)) return addslashes($string);  
  19. <span style="white-space:pre">      </span>foreach($string as $key => $val) $string[$key] = new_addslashes($val);  
  20. <span style="white-space:pre">      </span>return $string;  
  21.    }  
  22.   
  23.   
  24.    function new_stripslashes($string)  
  25.    {  
  26. <span style="white-space:pre">      </span>if(!is_array($string)) return stripslashes($string);  
  27. <span style="white-space:pre">      </span>foreach($string as $key => $val) $string[$key] = new_stripslashes($val);  
  28. <span style="white-space:pre">      </span>return $string;  
  29.    }  
  30.   
  31.   
  32.    function strip_textarea($string){  
  33. <span style="white-space:pre">      </span>return nl2br(str_replace(' ', '&nbsp;', htmlspecialchars($string, ENT_QUOTES)));  
  34.    }  
  35.   
  36.   
  37.    function strip_js($string, $js = 1){  
  38. <span style="white-space:pre">      </span>$string = str_replace(array("\n","\r","\""),array('','',"\\\""),$string);  
  39. <span style="white-space:pre">      </span>return $js==1 ? "document.write(\"".$string."\");\n" : $string;  
  40.    }  
  41.      
  42.    //邮件格式验证的函数  
  43.    function check_email($email)  
  44.    {  
  45.    <span style="white-space:pre"> </span>if(!preg_match("/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/",$email))  
  46.    <span style="white-space:pre"> </span>{  
  47.    <span style="white-space:pre">     </span>return false;  
  48.    <span style="white-space:pre"> </span>}  
  49.    <span style="white-space:pre"> </span>else  
  50.    <span style="white-space:pre">     </span>return true;  
  51.    }  
  52.      
  53.    //验证手机号码  
  54.    function check_mobile($mobile)  
  55.    {  
  56.    <span style="white-space:pre">     </span>$pattern = "/^1\d{10}$/";  
  57.    <span style="white-space:pre">     </span>if (preg_match($pattern,$mobile))  
  58.    <span style="white-space:pre">     </span>{  
  59.    <span style="white-space:pre">         </span>Return true;  
  60.    <span style="white-space:pre">     </span>}  
  61.    <span style="white-space:pre">     </span>else  
  62.    <span style="white-space:pre">     </span>{  
  63.    <span style="white-space:pre">         </span>Return false;  
  64.    <span style="white-space:pre">     </span>}  
  65.    }  
  66.      
  67.    //获取GMTime  
  68.    function get_gmtime()  
  69.    {  
  70.    <span style="white-space:pre"> </span>return (time() - date('Z'));  
  71.    }  
  72.      
  73.    function to_date($utc_time, $format = 'Y-m-d H:i:s') {  
  74.    <span style="white-space:pre"> </span>if (empty ( $utc_time )) {  
  75.    <span style="white-space:pre">     </span>return '';  
  76.    <span style="white-space:pre"> </span>}  
  77.    <span style="white-space:pre"> </span>$timezone = 8;  
  78.    <span style="white-space:pre"> </span>$time = $utc_time + $timezone * 3600;  
  79.    <span style="white-space:pre"> </span>return date ($format, $time );  
  80.    }  
  81.      
  82.      
  83.    function to_timespan($str, $format = 'Y-m-d H:i:s')  
  84.    {  
  85.    <span style="white-space:pre"> </span>$timezone = 8;  
  86.    <span style="white-space:pre"> </span>$time = intval(strtotime($str));  
  87.    <span style="white-space:pre"> </span>if($time!=0)  
  88.    <span style="white-space:pre">     </span>$time = $time - $timezone * 3600;  
  89.    <span style="white-space:pre"> </span>return $time;  
  90.    }  
  91.      
  92.    function get_http()  
  93.    {  
  94.    <span style="white-space:pre"> </span>return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';  
  95.    }  
  96.      
  97.    function get_domain()  
  98.    {  
  99.    <span style="white-space:pre"> </span>/* 协议 */  
  100.    <span style="white-space:pre"> </span>$protocol = get_http();  
  101.      
  102.    <span style="white-space:pre"> </span>/* 域名或IP地址 */  
  103.    <span style="white-space:pre"> </span>if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))  
  104.    <span style="white-space:pre"> </span>{  
  105.    <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_X_FORWARDED_HOST'];  
  106.    <span style="white-space:pre"> </span>}  
  107.    <span style="white-space:pre"> </span>elseif (isset($_SERVER['HTTP_HOST']))  
  108.    <span style="white-space:pre"> </span>{  
  109.    <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_HOST'];  
  110.    <span style="white-space:pre"> </span>}  
  111.    <span style="white-space:pre"> </span>else  
  112.    <span style="white-space:pre"> </span>{  
  113.    <span style="white-space:pre">     </span>/* 端口 */  
  114.    <span style="white-space:pre">     </span>if (isset($_SERVER['SERVER_PORT']))  
  115.    <span style="white-space:pre">     </span>{  
  116.    <span style="white-space:pre">         </span>$port = ':' . $_SERVER['SERVER_PORT'];  
  117.      
  118.    <span style="white-space:pre">         </span>if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))  
  119.    <span style="white-space:pre">         </span>{  
  120.    <span style="white-space:pre">             </span>$port = '';  
  121.    <span style="white-space:pre">         </span>}  
  122.    <span style="white-space:pre">     </span>}  
  123.    <span style="white-space:pre">     </span>else  
  124.    <span style="white-space:pre">     </span>{  
  125.    <span style="white-space:pre">         </span>$port = '';  
  126.    <span style="white-space:pre">     </span>}  
  127.      
  128.    <span style="white-space:pre">     </span>if (isset($_SERVER['SERVER_NAME']))  
  129.    <span style="white-space:pre">     </span>{  
  130.    <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_NAME'] . $port;  
  131.    <span style="white-space:pre">     </span>}  
  132.    <span style="white-space:pre">     </span>elseif (isset($_SERVER['SERVER_ADDR']))  
  133.    <span style="white-space:pre">     </span>{  
  134.    <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_ADDR'] . $port;  
  135.    <span style="white-space:pre">     </span>}  
  136.    <span style="white-space:pre"> </span>}  
  137.      
  138.    <span style="white-space:pre"> </span>return $protocol . $host;  
  139.    }  
  140.    function get_host()  
  141.    {  
  142.      
  143.      
  144.    <span style="white-space:pre"> </span>/* 域名或IP地址 */  
  145.    <span style="white-space:pre"> </span>if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))  
  146.    <span style="white-space:pre"> </span>{  
  147.    <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_X_FORWARDED_HOST'];  
  148.    <span style="white-space:pre"> </span>}  
  149.    <span style="white-space:pre"> </span>elseif (isset($_SERVER['HTTP_HOST']))  
  150.    <span style="white-space:pre"> </span>{  
  151.    <span style="white-space:pre">     </span>$host = $_SERVER['HTTP_HOST'];  
  152.    <span style="white-space:pre"> </span>}  
  153.    <span style="white-space:pre"> </span>else  
  154.    <span style="white-space:pre"> </span>{  
  155.    <span style="white-space:pre">     </span>if (isset($_SERVER['SERVER_NAME']))  
  156.    <span style="white-space:pre">     </span>{  
  157.    <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_NAME'];  
  158.    <span style="white-space:pre">     </span>}  
  159.    <span style="white-space:pre">     </span>elseif (isset($_SERVER['SERVER_ADDR']))  
  160.    <span style="white-space:pre">     </span>{  
  161.    <span style="white-space:pre">         </span>$host = $_SERVER['SERVER_ADDR'];  
  162.    <span style="white-space:pre">     </span>}  
  163.    <span style="white-space:pre"> </span>}  
  164.    <span style="white-space:pre"> </span>return $host;  
  165.    }  
  166.      
  167. /* 
  168.  * 实现AES加密 
  169. * $str : 要加密的字符串 
  170. * $keys : 加密密钥 
  171. * $iv : 加密向量 
  172. * $cipher_alg : 加密方式 
  173. */  
  174. function aes_ecryptdString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){  
  175. // <span style="white-space:pre">   </span>$encrypted_string= base64_encode(bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv)));  
  176. <span style="white-space:pre">  </span>$encrypted_string= bin2hex(mcrypt_encrypt($cipher_alg,$keys, $str, MCRYPT_MODE_CBC,$iv));  
  177. <span style="white-space:pre">  </span>return $encrypted_string;  
  178. }  
  179.   
  180.   
  181. /* 
  182.  * 实现AES解密 
  183. * $str : 要解密的字符串 
  184. * $keys : 加密密钥 
  185. * $iv : 加密向量 
  186. * $cipher_alg : 加密方式 
  187. */  
  188. function aes_decryptString($str,$keys="1034567890666450",$iv="1034567890123450",$cipher_alg=MCRYPT_RIJNDAEL_128){  
  189. // <span style="white-space:pre">   </span>$str= base64_decode($str);  
  190. <span style="white-space:pre">  </span>$decrypted_string= mcrypt_decrypt($cipher_alg,$keys,pack("H*",$str),MCRYPT_MODE_CBC,$iv);  
  191. <span style="white-space:pre">  </span>return $decrypted_string;  
  192. }  
  193.      
  194. /** 
  195.  * 对数组进行转码操作 
  196.  * @param $array 
  197.  * @param $in_charset 
  198.  * @param $out_charset 
  199.  */  
  200. function iconv_array(&$array,$in_charset,$out_charset)  
  201. {  
  202. <span style="white-space:pre">  </span>if(UC_CHARSET!='utf-8')  
  203. <span style="white-space:pre">  </span>{  
  204. <span style="white-space:pre">      </span>foreach($array as $k=>$v)  
  205. <span style="white-space:pre">      </span>{  
  206. <span style="white-space:pre">          </span>if(is_array($array[$k]))  
  207. <span style="white-space:pre">          </span>{  
  208. <span style="white-space:pre">              </span>iconv_array($array[$k],$in_charset,$out_charset);  
  209. <span style="white-space:pre">          </span>}  
  210. <span style="white-space:pre">          </span>else  
  211. <span style="white-space:pre">          </span>{  
  212. <span style="white-space:pre">              </span>$array[$k] = iconv($in_charset,$out_charset,$array[$k]);  
  213. <span style="white-space:pre">          </span>}  
  214. <span style="white-space:pre">      </span>}  
  215. <span style="white-space:pre">  </span>}  
  216. }  
  217.   
  218.   
  219. /** 
  220.  * utf8字符转Unicode字符 
  221.  * @param string $char 要转换的单字符 
  222.  * @return void 
  223.  */  
  224. function utf8_to_unicode($char)  
  225. {  
  226. <span style="white-space:pre">  </span>switch(strlen($char))  
  227. <span style="white-space:pre">  </span>{  
  228. <span style="white-space:pre">      </span>case 1:  
  229. <span style="white-space:pre">          </span>return ord($char);  
  230. <span style="white-space:pre">      </span>case 2:  
  231. <span style="white-space:pre">          </span>$n = (ord($char[0]) & 0x3f) << 6;  
  232. <span style="white-space:pre">          </span>$n += ord($char[1]) & 0x3f;  
  233. <span style="white-space:pre">          </span>return $n;  
  234. <span style="white-space:pre">      </span>case 3:  
  235. <span style="white-space:pre">          </span>$n = (ord($char[0]) & 0x1f) << 12;  
  236. <span style="white-space:pre">          </span>$n += (ord($char[1]) & 0x3f) << 6;  
  237. <span style="white-space:pre">          </span>$n += ord($char[2]) & 0x3f;  
  238. <span style="white-space:pre">          </span>return $n;  
  239. <span style="white-space:pre">      </span>case 4:  
  240. <span style="white-space:pre">          </span>$n = (ord($char[0]) & 0x0f) << 18;  
  241. <span style="white-space:pre">          </span>$n += (ord($char[1]) & 0x3f) << 12;  
  242. <span style="white-space:pre">          </span>$n += (ord($char[2]) & 0x3f) << 6;  
  243. <span style="white-space:pre">          </span>$n += ord($char[3]) & 0x3f;  
  244. <span style="white-space:pre">          </span>return $n;  
  245. <span style="white-space:pre">  </span>}  
  246. }  
  247.   
  248.   
  249. /** 
  250.  * utf8字符串分隔为unicode字符串 
  251.  * @param string $str 要转换的字符串 
  252.  * @param string $depart 分隔,默认为空格为单字 
  253.  * @return string 
  254.  */  
  255. function str_to_unicode_word($str,$depart=' ')  
  256. {  
  257. <span style="white-space:pre">  </span>$arr = array();  
  258. <span style="white-space:pre">  </span>$str_len = mb_strlen($str,'utf-8');  
  259. <span style="white-space:pre">  </span>for($i = 0;$i < $str_len;$i++)  
  260. <span style="white-space:pre">  </span>{  
  261. <span style="white-space:pre">      </span>$s = mb_substr($str,$i,1,'utf-8');  
  262. <span style="white-space:pre">      </span>if($s != ' ' && $s != ' ')  
  263. <span style="white-space:pre">          </span>{  
  264. <span style="white-space:pre">          </span>$arr[] = 'ux'.utf8_to_unicode($s);  
  265. <span style="white-space:pre">      </span>}  
  266. <span style="white-space:pre">  </span>}  
  267. return implode($depart,$arr);  
  268. }  
  269.   
  270.   
  271. /** 
  272.  * utf8字符串分隔为unicode字符串 
  273.  * @param string $str 要转换的字符串 
  274.  * @return string 
  275.  */  
  276. function str_to_unicode_string($str)  
  277. {  
  278. <span style="white-space:pre">  </span>$string = str_to_unicode_word($str,'');  
  279. <span style="white-space:pre">  </span>return $string;  
  280. }  
  281.   
  282.   
  283. //分词  
  284. function div_str($str)  
  285. {  
  286. <span style="white-space:pre">  </span>require_once APP_ROOT_PATH."core/lib/words.php";  
  287. <span style="white-space:pre">  </span>$words = words::segment($str);  
  288. <span style="white-space:pre">  </span>$words[] = $str;  
  289. <span style="white-space:pre">  </span>return $words;  
  290. }  
  291.   
  292.   
  293. /** 
  294.  * @desc  im:十进制数转换成三十六机制数 
  295.  * @param (int)$num 十进制数 
  296.  * return 返回:三十六进制数 
  297.  */  
  298. function get_code_bynum($num) {  
  299. <span style="white-space:pre">  </span>$num = intval($num);  
  300. <span style="white-space:pre">  </span>if ($num <= 0)  
  301. <span style="white-space:pre">      </span>return false;  
  302. <span style="white-space:pre">  </span>$codeArr = array("0","1","2","3","4","5","6","7","8","9",'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');  
  303. <span style="white-space:pre">  </span>$code = '';  
  304. <span style="white-space:pre">  </span>do {  
  305. <span style="white-space:pre">      </span>$key = ($num - 1) % 36;  
  306. <span style="white-space:pre">      </span>$code = $codeArr[$key] . $code;  
  307. <span style="white-space:pre">      </span>$num = floor(($num - $key) / 36);  
  308. <span style="white-space:pre">  </span>} while ($num > 0);  
  309. <span style="white-space:pre">  </span>return $code;  
  310. }  
  311.   
  312.   
  313. /** 
  314.  * @desc  im:三十六进制数转换成十机制数 
  315.  * @param (string)$str 三十六进制数 
  316.  * return 返回:十进制数 
  317.  */  
  318. function get_num_bycode($str){  
  319. <span style="white-space:pre">  </span>$array=array("0","1","2","3","4","5","6","7","8","9","A", "B", "C", "D","E", "F", "G", "H", "I", "J", "K", "L","M", "N", "O","P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y","Z");  
  320. <span style="white-space:pre">  </span>$len=strlen($str);  
  321. <span style="white-space:pre">  </span>for($i=0;$i<$len;$i++){  
  322. <span style="white-space:pre">      </span>$index=array_search($str[$i],$array);  
  323. <span style="white-space:pre">      </span>$sum+=($index+1)*pow(36,$len-$i-1);  
  324. <span style="white-space:pre">  </span>}  
  325. <span style="white-space:pre">  </span>return $sum;  
  326. }  
  327.   
  328.   
  329. ?>  

5.加载公共方法的文件./core/common.php 源码:

[php] view plain copy
 
  1. <?php  
  2. function app_conf($name)  
  3. {  
  4.     return  $GLOBALS['db']->getOne("select value from ".DB_PREFIX."conf where name='".$name."'");  
  5. }  
  6.   
  7. /* 
  8.  * @des:im:验证手机号码 
  9. * @param:$phone 
  10. */  
  11. function check_phone($phone)  
  12. {  
  13.     if(!empty($phone) && !preg_match("/^1\d{10}$/",$phone))  
  14.     {  
  15.         return false;  
  16.     }  
  17.     else  
  18.         return true;  
  19. }  
  20.   
  21. /** 
  22.  * @desc  get_pwd_strength()im:根据密码字符串判断密码结构 
  23.  * @param (string)$mobile 
  24.  * return 返回:$msg 
  25.  */  
  26. function get_pwd_strength($pwd){  
  27.     if (strlen(iconv('UTF-8','GBK',$pwd))>30 || strlen(iconv('UTF-8','GBK',$pwd))<6)  
  28.     {  
  29.         return '密码是6-30位的字符串,且必须由字母和数字组成.';  
  30.     }  
  31.   
  32.     if(preg_match("/^\d+$/",$pwd))  
  33.     {  
  34.         return '密码不能为全数字';//全数字  
  35.     }  
  36.   
  37.     if(preg_match("/^[a-z]+$/i",$pwd))  
  38.     {  
  39.         return '密码不能为全字母';//全字母  
  40.     }  
  41.   
  42.     if(!preg_match("/^[A-Za-z0-9]+$/",$pwd))  
  43.     {  
  44.         return '密码只能包含字母和数字';//有数字有字母   ";  
  45.     }  
  46.     return null;  
  47. }  
  48.   
  49.   
  50. /*ajax返回*/  
  51. function ajax_return($data)  
  52. {  
  53.     header("Content-Type:text/html; charset=utf-8");  
  54.     echo(json_encode($data));  
  55. //  echo(base64_encode(json_encode($data)));  
  56.     if (APP_LOG) {  
  57.         $GLOBALS['log']->quit($data);  
  58.     }  
  59.     exit;  
  60. }  
  61.   
  62. /** 
  63.  * 字符串加密函数 
  64.  * @param string $txt 
  65.  * @param string $key 
  66.  * @return string 
  67.  */  
  68. function passport_encrypt($txt, $key = 'IMEMBER_2013') {  
  69.     srand((double)microtime() * 1000000);  
  70.     $encrypt_key = md5(rand(0, 32000));  
  71.     $ctr = 0;  
  72.     $tmp = '';  
  73.     for($i = 0;$i < strlen($txt); $i++) {  
  74.         $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;  
  75.         $tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);  
  76.     }  
  77.     return base64_encode(passport_key($tmp, $key));  
  78. }  
  79.   
  80. /** 
  81.  * 字符串解密函数 
  82.  * @param string $txt 
  83.  * @param string $key 
  84.  * @return string 
  85.  */  
  86. function passport_decrypt($txt, $key = 'IMEMBER_2013') {  
  87.     $txt = passport_key(base64_decode($txt), $key);  
  88.     $tmp = '';  
  89.     for($i = 0;$i < strlen($txt); $i++) {  
  90.         if (empty($txt[$i+1])) {  
  91.             return false;  
  92.         }  
  93.         $md5 = $txt[$i];  
  94.         $tmp .= $txt[++$i] ^ $md5;  
  95.     }  
  96.     return $tmp;  
  97. }  
  98.   
  99. function passport_key($txt, $encrypt_key) {  
  100.     $encrypt_key = md5($encrypt_key);  
  101.     $ctr = 0;  
  102.     $tmp = '';  
  103.     for($i = 0; $i < strlen($txt); $i++) {  
  104.         $ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;  
  105.         $tmp .= $txt[$i] ^ $encrypt_key[$ctr++];  
  106.     }  
  107.     return $tmp;  
  108. }  
  109.   
  110. /** 
  111.  * 传入图片的地址,自动修复图片的相对路径(如 ./public/logo.png)到绝对路径(如http://www.imember.cc/public/logo.png) 
  112.  * @param unknown $img_path 
  113.  */  
  114. function imagePathRevise($img_path){  
  115.     //判断$img_path的路径是否以http://开头  
  116.     if (preg_match('/^http:\/\//', $img_path)) {  
  117.         return $img_path;  
  118.     }else{  
  119.         return IMG_PATH.preg_replace('/^\.\//', '', $img_path);  
  120.     }  
  121. }  
  122.   
  123. //utf8 字符串截取  
  124. function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true)  
  125. {  
  126.     if(function_exists("mb_substr"))  
  127.     {  
  128.         $slice =  mb_substr($str, $start, $length, $charset);  
  129.         if($suffix&$slice!=$str) return $slice."…";  
  130.         return $slice;  
  131.     }  
  132.     elseif(function_exists('iconv_substr')) {  
  133.         return iconv_substr($str,$start,$length,$charset);  
  134.     }  
  135.     $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";  
  136.     $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";  
  137.     $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";  
  138.     $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";  
  139.     preg_match_all($re[$charset], $str, $match);  
  140.     $slice = join("",array_slice($match[0], $start, $length));  
  141.     if($suffix&&$slice!=$str) return $slice."…";  
  142.     return $slice;  
  143. }  
  144.   
  145. }  
  146. ?>  

 

6.加载./initializer.php,initializer()用于将所有公用的文件目录在此函数里声明

initializer::initialize();
这就话就是调用initializer类的一个静态函数initialize,因为我们在ini.php,设置了include_path,以及定义了__autoload,所以程序会自动在core/main目录查找initializer.php.
定义了一个静态函数,initialize函数,这个函数就是设置include_path,这样,以后如果包含文件,或者__autoload,就会去这些目录下查找。

 

[php] view plain copy
 
  1. <?php  
  2. class initializer  
  3. {  
  4.     public static function initialize() {  
  5.         set_include_path(get_include_path().PATH_SEPARATOR . "core/main");  
  6.         set_include_path(get_include_path().PATH_SEPARATOR . "core/main/cache");  
  7.         set_include_path(get_include_path().PATH_SEPARATOR . "core/helpers");  
  8.         set_include_path(get_include_path().PATH_SEPARATOR . "core/libraries");  
  9.         set_include_path(get_include_path().PATH_SEPARATOR . "core/config");  
  10.         set_include_path(get_include_path().PATH_SEPARATOR . "app/controllers");  
  11.         set_include_path(get_include_path().PATH_SEPARATOR."app/models");  
  12.         set_include_path(get_include_path().PATH_SEPARATOR."app/views");  
  13.   
  14.     }  
  15. }  
  16. ?>  

 

7.加载./loader.php文件,源码:

 

 

[php] view plain copy
 
  1. <?php  
  2. class loader  
  3. {  
  4.     private static $loaded = array();  
  5.     public static function load($object){  
  6.         $valid = array(   
  7.                 "library",  
  8.                 "view",  
  9.                 "model",  
  10.                 "helper",  
  11.                 "router",  
  12.                 "config",  
  13.                 "hook",  
  14.                 "cache",  
  15.                 "db");  
  16.         if (!in_array($object,$valid)){  
  17. //          throw new Exception("Not a valid object '{$object}' to load");  
  18.             ajax_return(array('recode'=>"0003",'msg'=>"非法操作","data"=>"Not a valid object '{$object}' to load"));  
  19.         }  
  20.         if (empty(self::$loaded[$object])){  
  21.             self::$loaded[$object]= new $object();  
  22.         }  
  23.         return self::$loaded[$object];  
  24.     }  
  25. }  
  26. ?>  

8.加载控制层文件./router.php,源码:

 

 

[php] view plain copy
 
  1. <?php  
  2. class router  
  3. {  
  4.     private $route;  
  5.     private $controller;  
  6.     private $action;  
  7.     private $params;  
  8.     public function __construct()  
  9.     {  
  10.         //base64_decode(str)解码  
  11.         $routeParts=$_GET;  
  12. //      $routeParts=base64_decode($_GET);  
  13.         if (!isset($routeParts['c'])){  
  14.             ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>"Controller is null"));  
  15.         }  
  16.           
  17.         $this->route = $routeParts['c'];  
  18.         $this->controller=$routeParts['c'];  
  19.         $this->action=isset($routeParts['act'])? $routeParts['act']:"index";  
  20.         array_shift($routeParts);  
  21.         array_shift($routeParts);  
  22.         $this->params=$routeParts;  
  23.     }  
  24.     public function getAction() {  
  25.         if (empty($this->action)) $this->action="index";  
  26.         return $this->action;  
  27.     }  
  28.     public function getController()  {  
  29.         return $this->controller;  
  30.     }  
  31.     public function getParams()  {  
  32.         return $this->params;  
  33.     }  
  34. }  
  35. ?>  

9.加载数据库连接文件./core/conn.php,源码:

 

 

[php] view plain copy
 
  1. <?php  
  2.    /* 
  3.    * 数据库连接 
  4.    */  
  5.     //第一种方法:直接写入数据库连接参数  
  6. //    $dblink=mysql_connect("127.0.0.1:3306","sara","abc123");  
  7. //    mysql_select_db("ipolarbear",$dblink);  
  8. //    mysql_query("SET NAMES UTF8");  
  9. //    if (!$dblink) {  
  10. //          mysql_query("SET NAMES UTF8");  
  11. //          die (json_encode(array('recode'=>"0009",'msg'=>"连接数据库失败" . mysql_error (),'data'=>'')));  
  12. //    }  
  13.   
  14.    //第二种方法:定义DB类,加载数据库配置,对数据库SQL进行封装  
  15.    //加载数据库配置  
  16.    $dbcfg = require APP_ROOT_PATH."core/config/db_config.php";  
  17.       
  18.     if(!defined('DB_PREFIX'))//im:数据库表前缀  
  19.         define('DB_PREFIX', $dbcfg['DB_PREFIX']);  
  20.    if(!file_exists(APP_ROOT_PATH.'core/runtime/db_caches/'))  
  21.         mkdir(APP_ROOT_PATH.'core/runtime/db_caches/',0777);  
  22.    $pconnect = false;  
  23.    $GLOBALS['db'] = new mysql_db($dbcfg['DB_HOST'].":".$dbcfg['DB_PORT'], $dbcfg['DB_USER'],$dbcfg['DB_PWD'],$dbcfg['DB_NAME'],'utf8',$pconnect);  
  24.    mysql_query("SET NAMES UTF8");//相当于character_set_client(),character_set_connection(),character_set_results()客户端 连接器 返回值三者同时设置编码方式  
  25.    //检查PHP是否连接上MYSQL  
  26.    if(mysqli_connect_errno()){  
  27.         die (json_encode(array('recode'=>"0009",'msg'=>"连接数据库失败:" . mysql_error (),'data'=>'')));  
  28.    }  
  29.    //end 定义DB  
  30.      
  31. ?>  

 

10.加载数据库配置文件./core/db_config.php,源码:

 

 

[php] view plain copy
 
  1. <?php  
  2. return array(  
  3. 'DB_HOST'=>'localhost',  
  4. 'DB_NAME'=>'ip',  
  5. 'DB_USER'=>'sara',  
  6. 'DB_PWD'=>'abc123',  
  7. 'DB_PORT'=>'3306',  
  8. 'DB_PREFIX'=>'base_',  
  9. );  
  10. ?>  


11.加载数据库类文件./core/mysql_db.php,源码:

[php] view plain copy
 
  1. <?php  
  2.       
  3.    class mysql_db  
  4.    {  
  5.     var $link_id    = NULL;  
  6.      
  7.     var $settings   = array();  
  8.      
  9.     var $queryCount = 0;  
  10.     var $queryTime  = '';  
  11.     var $queryLog   = array();  
  12.      
  13.     var $max_cache_time = 60; // 最大的缓存时间,以秒为单位  
  14.      
  15.     var $cache_data_dir = 'core/runtime/db_caches/';  
  16.     var $root_path      = '';  
  17.      
  18.     var $error_message  = array();  
  19.     var $platform       = '';  
  20.     var $version        = '';  
  21.     var $dbhash         = '';  
  22.     var $starttime      = 0;  
  23.     var $timeline       = 0;  
  24.     var $timezone       = 0;  
  25.   
  26.     var $mysql_config_cache_file_time = 0;  
  27.      
  28.     var $mysql_disable_cache_tables = array(); // 不允许被缓存的表,遇到将不会进行缓存  
  29.      
  30.     function __construct($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)  
  31.     {  
  32.         $this->mysql_db($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);  
  33.     }  
  34.      
  35.     function mysql_db($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)  
  36.     {  
  37.         if (defined('APP_ROOT_PATH') && !$this->root_path)  
  38.         {  
  39.             $this->root_path = APP_ROOT_PATH;  
  40.         }  
  41.      
  42.         if ($quiet)  
  43.         {  
  44.             $this->connect($dbhost, $dbuser, $dbpw, $dbname, $charset, $pconnect, $quiet);  
  45.         }  
  46.         else  
  47.         {  
  48.             $this->settings = array(  
  49.                     'dbhost'   => $dbhost,  
  50.                     'dbuser'   => $dbuser,  
  51.                     'dbpw'     => $dbpw,  
  52.                     'dbname'   => $dbname,  
  53.                     'charset'  => $charset,  
  54.                     'pconnect' => $pconnect  
  55.             );  
  56.         }  
  57.     }  
  58.      
  59.     function connect($dbhost, $dbuser, $dbpw, $dbname = '', $charset = 'utf8', $pconnect = 0, $quiet = 0)  
  60.     {  
  61.         if ($pconnect)  
  62.         {  
  63.             if (!($this->link_id = @mysql_pconnect($dbhost, $dbuser, $dbpw)))  
  64.             {  
  65.                 if (!$quiet)  
  66.                 {  
  67.                     $this->ErrorMsg("Can't pConnect MySQL Server($dbhost)!");  
  68.                 }  
  69.      
  70.                 return false;  
  71.             }  
  72.         }  
  73.         else  
  74.         {  
  75.             if (PHP_VERSION >= '4.2')  
  76.             {  
  77.                 $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw, true);  
  78.             }  
  79.             else  
  80.             {  
  81.                 $this->link_id = @mysql_connect($dbhost, $dbuser, $dbpw);  
  82.      
  83.                 mt_srand((double)microtime() * 1000000); // 对 PHP 4.2 以下的版本进行随机数函数的初始化工作  
  84.             }  
  85.             if (!$this->link_id)  
  86.             {  
  87.                 if (!$quiet)  
  88.                 {  
  89.                     $this->ErrorMsg("Can't Connect MySQL Server($dbhost)!");  
  90.                 }  
  91.      
  92.                 return false;  
  93.             }  
  94.         }  
  95.      
  96.         $this->dbhash  = md5($this->root_path . $dbhost . $dbuser . $dbpw . $dbname);  
  97.         $this->version = mysql_get_server_info($this->link_id);  
  98.      
  99.         /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */  
  100.         if ($this->version > '4.1')  
  101.         {  
  102.             if ($charset != 'latin1')  
  103.             {  
  104.                 mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);  
  105.             }  
  106.             if ($this->version > '5.0.1')  
  107.             {  
  108.                 mysql_query("SET sql_mode=''", $this->link_id);  
  109.             }  
  110.         }  
  111.      
  112.         $sqlcache_config_file = $this->root_path . $this->cache_data_dir . 'sqlcache_config_file_' . $this->dbhash . '.php';  
  113.      
  114.         @include($sqlcache_config_file);  
  115.      
  116.         $this->starttime = time();  
  117.      
  118.         if ($this->max_cache_time && $this->starttime > $this->mysql_config_cache_file_time + $this->max_cache_time)  
  119.         {  
  120.             if ($dbhost != '.')  
  121.             {  
  122.                 $result = mysql_query("SHOW VARIABLES LIKE 'basedir'", $this->link_id);  
  123.                 $row    = mysql_fetch_assoc($result);  
  124.                 if (!empty($row['Value']{  
  125.                     1}) && $row['Value']{  
  126.                         1} == ':' && !empty($row['Value']{  
  127.                             2}) && $row['Value']{  
  128.                                 2} == "\\")  
  129.                 {  
  130.                     $this->platform = 'WINDOWS';  
  131.                 }  
  132.                 else  
  133.                 {  
  134.                     $this->platform = 'OTHER';  
  135.                 }  
  136.             }  
  137.             else  
  138.             {  
  139.                 $this->platform = 'WINDOWS';  
  140.             }  
  141.      
  142.             if ($this->platform == 'OTHER' &&  
  143.                     ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306') ||  
  144.                     (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC'))  
  145.             {  
  146.                 $result = mysql_query("SELECT UNIX_TIMESTAMP() AS timeline, UNIX_TIMESTAMP('" . date('Y-m-d H:i:s', $this->starttime) . "') AS timezone", $this->link_id);  
  147.                 $row    = mysql_fetch_assoc($result);  
  148.      
  149.                 if ($dbhost != '.' && strtolower($dbhost) != 'localhost:3306' && $dbhost != '127.0.0.1:3306')  
  150.                 {  
  151.                     $this->timeline = $this->starttime - $row['timeline'];  
  152.                 }  
  153.      
  154.                 if (PHP_VERSION >= '5.1' && date_default_timezone_get() == 'UTC')  
  155.                 {  
  156.                     $this->timezone = $this->starttime - $row['timezone'];  
  157.                 }  
  158.             }  
  159.      
  160.             $content = '<' . "?php\r\n" .  
  161.                     '$this->mysql_config_cache_file_time = ' . $this->starttime . ";\r\n" .  
  162.                     '$this->timeline = ' . $this->timeline . ";\r\n" .  
  163.                     '$this->timezone = ' . $this->timezone . ";\r\n" .  
  164.                     '$this->platform = ' . "'" . $this->platform . "';\r\n?" . '>';  
  165.      
  166.             @file_put_contents($sqlcache_config_file, $content);  
  167.         }  
  168.      
  169.         /* 选择数据库 */  
  170.         if ($dbname)  
  171.         {  
  172.             if (mysql_select_db($dbname, $this->link_id) === false )  
  173.             {  
  174.                 if (!$quiet)  
  175.                 {  
  176.                     $this->ErrorMsg("Can't select MySQL database($dbname)!");  
  177.                 }  
  178.      
  179.                 return false;  
  180.             }  
  181.             else  
  182.             {  
  183.                 return true;  
  184.             }  
  185.         }  
  186.         else  
  187.         {  
  188.             return true;  
  189.         }  
  190.     }  
  191.      
  192.     function select_database($dbname)  
  193.     {  
  194.         return mysql_select_db($dbname, $this->link_id);  
  195.     }  
  196.      
  197.     function set_mysql_charset($charset)  
  198.     {  
  199.         /* 如果mysql 版本是 4.1+ 以上,需要对字符集进行初始化 */  
  200.         if ($this->version > '4.1')  
  201.         {  
  202.             if (in_array(strtolower($charset), array('gbk', 'big5', 'utf-8', 'utf8')))  
  203.             {  
  204.                 $charset = str_replace('-', '', $charset);  
  205.             }  
  206.             if ($charset != 'latin1')  
  207.             {  
  208.                 mysql_query("SET character_set_connection=$charset, character_set_results=$charset, character_set_client=binary", $this->link_id);  
  209.             }  
  210.         }  
  211.     }  
  212.      
  213.     function fetch_array($query, $result_type = MYSQL_ASSOC)  
  214.     {  
  215.         return mysql_fetch_array($query, $result_type);  
  216.     }  
  217.      
  218.     function query($sql, $type = '')  
  219.     {  
  220.         if ($this->link_id === NULL)  
  221.         {  
  222.             $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']);  
  223.             $this->settings = array();  
  224.         }  
  225.      
  226.         if ($this->queryCount++ <= 99)  
  227.         {  
  228.             $this->queryLog[] = $sql;  
  229.         }  
  230.         if ($this->queryTime == '')  
  231.         {  
  232.             if (PHP_VERSION >= '5.0.0')  
  233.             {  
  234.                 $this->queryTime = microtime(true);  
  235.             }  
  236.             else  
  237.             {  
  238.                 $this->queryTime = microtime();  
  239.             }  
  240.         }  
  241.      
  242.         /* 当当前的时间大于类初始化时间的时候,自动执行 ping 这个自动重新连接操作 */  
  243.         if (PHP_VERSION >= '4.3' && time() > $this->starttime + 1)  
  244.         {  
  245.             mysql_ping($this->link_id);  
  246.         }  
  247.      
  248.         if (!($query = mysql_query($sql, $this->link_id)) && $type != 'SILENT')  
  249.         {  
  250.             $this->error_message[]['message'] = 'MySQL Query Error';  
  251.             $this->error_message[]['sql'] = $sql;  
  252.             $this->error_message[]['error'] = mysql_error($this->link_id);  
  253.             $this->error_message[]['errno'] = mysql_errno($this->link_id);  
  254.      
  255.             $this->ErrorMsg();  
  256.      
  257.             return false;  
  258.         }  
  259.      
  260.         if (defined('DEBUG_MODE') && (DEBUG_MODE & 8) == 8)  
  261.         {  
  262.             $logfilename = $this->root_path . DATA_DIR . '/mysql_query_' . $this->dbhash . '_' . date('Y_m_d') . '.log';  
  263.             $str = $sql . "\n\n";  
  264.      
  265.             if (PHP_VERSION >= '5.0')  
  266.             {  
  267.                 file_put_contents($logfilename, $str, FILE_APPEND);  
  268.             }  
  269.             else  
  270.             {  
  271.                 $fp = @fopen($logfilename, 'ab+');  
  272.                 if ($fp)  
  273.                 {  
  274.                     fwrite($fp, $str);  
  275.                     fclose($fp);  
  276.                 }  
  277.             }  
  278.         }  
  279.         //echo $sql."<br/><br/>======================================<br/><br/>";  
  280.         return $query;  
  281.     }  
  282.      
  283.     function affected_rows()  
  284.     {  
  285.         return mysql_affected_rows($this->link_id);  
  286.     }  
  287.      
  288.     function error()  
  289.     {  
  290.         return mysql_error($this->link_id);  
  291.     }  
  292.      
  293.     function errno()  
  294.     {  
  295.         return mysql_errno($this->link_id);  
  296.     }  
  297.      
  298.     function result($query, $row)  
  299.     {  
  300.         return @mysql_result($query, $row);  
  301.     }  
  302.      
  303.     function num_rows($query)  
  304.     {  
  305.         return mysql_num_rows($query);  
  306.     }  
  307.      
  308.     function num_fields($query)  
  309.     {  
  310.         return mysql_num_fields($query);  
  311.     }  
  312.      
  313.     function free_result($query)  
  314.     {  
  315.         return mysql_free_result($query);  
  316.     }  
  317.      
  318.     function insert_id()  
  319.     {  
  320.         return mysql_insert_id($this->link_id);  
  321.     }  
  322.      
  323.     function fetchRow($query)  
  324.     {  
  325.         return mysql_fetch_assoc($query);  
  326.     }  
  327.      
  328.     function fetch_fields($query)  
  329.     {  
  330.         return mysql_fetch_field($query);  
  331.     }  
  332.      
  333.     function version()  
  334.     {  
  335.         return $this->version;  
  336.     }  
  337.      
  338.     function ping()  
  339.     {  
  340.         if (PHP_VERSION >= '4.3')  
  341.         {  
  342.             return mysql_ping($this->link_id);  
  343.         }  
  344.         else  
  345.         {  
  346.             return false;  
  347.         }  
  348.     }  
  349.      
  350.     function escape_string($unescaped_string)  
  351.     {  
  352.         if (PHP_VERSION >= '4.3')  
  353.         {  
  354.             return mysql_real_escape_string($unescaped_string);  
  355.         }  
  356.         else  
  357.         {  
  358.             return mysql_escape_string($unescaped_string);  
  359.         }  
  360.     }  
  361.      
  362.     function close()  
  363.     {  
  364.         return mysql_close($this->link_id);  
  365.     }  
  366.      
  367.     function ErrorMsg($message = '', $sql = '')  
  368.     {  
  369.         if ($message)  
  370.         {  
  371.             ajax_return(array('recode'=>"0009",'msg'=>"MySQL server error info:".$message,'data'=>''));  
  372.         }  
  373.         else  
  374.         {  
  375.             ajax_return(array('recode'=>"0010",'msg'=>"MySQL server error report:".$this->error_message,'data'=>''));  
  376.         }  
  377.      }  
  378.      
  379.     /* 仿真 Adodb 函数 */  
  380.     function selectLimit($sql, $num, $start = 0)  
  381.     {  
  382.     if ($start == 0)  
  383.     {  
  384.         $sql .= ' LIMIT ' . $num;  
  385.         }  
  386.         else  
  387.         {  
  388.         $sql .= ' LIMIT ' . $start . ', ' . $num;  
  389.     }  
  390.      
  391.     return $this->query($sql);  
  392.     }  
  393.      
  394.     function getOne($sql, $limited = false)  
  395.     {  
  396.     if ($limited == true)  
  397.     {  
  398.     $sql = trim($sql . ' LIMIT 1');  
  399.     }  
  400.      
  401.     $res = $this->query($sql);  
  402.     if ($res !== false)  
  403.     {  
  404.     $row = mysql_fetch_row($res);  
  405.      
  406.     if ($row !== false)  
  407.     {  
  408.         return $row[0];  
  409.         }  
  410.         else  
  411.         {  
  412.             return '';  
  413.     }  
  414.     }  
  415.     else  
  416.     {  
  417.     return false;  
  418.     }  
  419.     }  
  420.      
  421.     function getOneCached($sql, $cached = 'FILEFIRST')  
  422.     {  
  423.      
  424.      
  425.     $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;  
  426.      
  427.     if (!$cachefirst)  
  428.     {  
  429.     return $this->getOne($sql, true);  
  430.     }  
  431.     else  
  432.     {  
  433.     $result = $this->getSqlCacheData($sql, $cached);  
  434.     if (empty($result['storecache']) == true)  
  435.     {  
  436.     return $result['data'];  
  437.             }  
  438.             }  
  439.      
  440.             $arr = $this->getOne($sql, true);  
  441.      
  442.             if ($arr !== false && $cachefirst)  
  443.             {  
  444.             $this->setSqlCacheData($result, $arr);  
  445.             }  
  446.      
  447.             return $arr;  
  448.             }  
  449.      
  450.             function getAll($sql)  
  451.             {  
  452.             $res = $this->query($sql);  
  453.             if ($res !== false)  
  454.             {  
  455.                 $arr = array();  
  456.                 while ($row = mysql_fetch_assoc($res))  
  457.                 {  
  458.                     $arr[] = $row;  
  459.                 }  
  460.      
  461.                 return $arr;  
  462.                 }  
  463.                 else  
  464.                 {  
  465.                 return false;  
  466.                 }  
  467.                 }  
  468.      
  469.                 function getAllCached($sql, $cached = 'FILEFIRST')  
  470.                 {  
  471.                 $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;  
  472.                 if (!$cachefirst)  
  473.                 {  
  474.                 return $this->getAll($sql);  
  475.                 }  
  476.                 else  
  477.                 {  
  478.                 $result = $this->getSqlCacheData($sql, $cached);  
  479.                 if (empty($result['storecache']) == true)  
  480.                 {  
  481.                 return $result['data'];  
  482.                 }  
  483.                 }  
  484.      
  485.                 $arr = $this->getAll($sql);  
  486.      
  487.                 if ($arr !== false && $cachefirst)  
  488.                 {  
  489.                     $this->setSqlCacheData($result, $arr);  
  490.                     }  
  491.      
  492.                     return $arr;  
  493.                     }  
  494.      
  495.                     function getRow($sql, $limited = false)  
  496.                     {  
  497.                             if ($limited == true)  
  498.                             {  
  499.                             $sql = trim($sql . ' LIMIT 1');  
  500.                             }  
  501.      
  502.                                     $res = $this->query($sql);  
  503.                                     if ($res !== false)  
  504.                                     {  
  505.                                     return mysql_fetch_assoc($res);  
  506.                                     }  
  507.                                     else  
  508.                                     {  
  509.                                     return false;  
  510.                                     }  
  511.                                     }  
  512.      
  513.                                     function getRowCached($sql, $cached = 'FILEFIRST')  
  514.                                     {  
  515.      
  516.      
  517.                                     $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;  
  518.                                     if (!$cachefirst)  
  519.                                     {  
  520.                                     return $this->getRow($sql, true);  
  521.                                     }  
  522.                                     else  
  523.                                     {  
  524.                                     $result = $this->getSqlCacheData($sql, $cached);  
  525.                                     if (empty($result['storecache']) == true)  
  526.                                     {  
  527.                                     return $result['data'];  
  528.                                     }  
  529.                                     }  
  530.      
  531.                                     $arr = $this->getRow($sql, true);  
  532.      
  533.                                     if ($arr !== false && $cachefirst)  
  534.                                     {  
  535.                                     $this->setSqlCacheData($result, $arr);  
  536.                                     }  
  537.      
  538.                                     return $arr;  
  539.                                     }  
  540.      
  541.                                     function getCol($sql)  
  542.                                     {  
  543.                                     $res = $this->query($sql);  
  544.                                     if ($res !== false)  
  545.                                     {  
  546.                                     $arr = array();  
  547.                                     while ($row = mysql_fetch_row($res))  
  548.                                     {  
  549.                                     $arr[] = $row[0];  
  550.                                     }  
  551.      
  552.                                     return $arr;  
  553.                                     }  
  554.                                     else  
  555.                                         {  
  556.                                         return false;  
  557.                                     }  
  558.                                     }  
  559.      
  560.                                     function getColCached($sql, $cached = 'FILEFIRST')  
  561.                                     {  
  562.                                     $cachefirst = ($cached == 'FILEFIRST' || ($cached == 'MYSQLFIRST' && $this->platform != 'WINDOWS')) && $this->max_cache_time;  
  563.                                     if (!$cachefirst)  
  564.                                     {  
  565.                                         return $this->getCol($sql);  
  566.                                     }  
  567.                                     else  
  568.                                     {  
  569.                                         $result = $this->getSqlCacheData($sql, $cached);  
  570.                                         if (empty($result['storecache']) == true)  
  571.                 {  
  572.                 return $result['data'];  
  573.                 }  
  574.                 }  
  575.      
  576.                 $arr = $this->getCol($sql);  
  577.      
  578.                 if ($arr !== false && $cachefirst)  
  579.                 {  
  580.                     $this->setSqlCacheData($result, $arr);  
  581.                 }  
  582.      
  583.                 return $arr;  
  584.                 }  
  585.      
  586.                 function autoExecute($table, $field_values, $mode = 'INSERT', $where = '', $querymode = '')  
  587.                 {  
  588.                 $field_names = $this->getCol('DESC ' . $table);  
  589.      
  590.                         $sql = '';  
  591.                         if ($mode == 'INSERT')  
  592.                         {  
  593.                         $fields = $values = array();  
  594.                         foreach ($field_names AS $value)  
  595.                         {  
  596.                         if (@array_key_exists($value, $field_values) == true)  
  597.                         {  
  598.                         $fields[] = $value;  
  599.                         $field_values[$value] = stripslashes($field_values[$value]);  
  600.                         $values[] = "'" . addslashes($field_values[$value]) . "'";  
  601.                         }  
  602.                         }  
  603.      
  604.                         if (!empty($fields))  
  605.                         {  
  606.                             $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';  
  607.                             }  
  608.                         }  
  609.                         else  
  610.                         {  
  611.                         $sets = array();  
  612.                         foreach ($field_names AS $value)  
  613.                         {  
  614.                         if (array_key_exists($value, $field_values) == true)  
  615.                         {  
  616.                         $field_values[$value] = stripslashes($field_values[$value]);  
  617.                         $sets[] = $value . " = '" . addslashes($field_values[$value]) . "'";  
  618.                         }  
  619.                         }  
  620.      
  621.                         if (!empty($sets))  
  622.                             {  
  623.                             $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;  
  624.                             }  
  625.                             }  
  626.      
  627.                             if ($sql)  
  628.                             {  
  629.                                 return $this->query($sql, $querymode);  
  630.                         }  
  631.                         else  
  632.                         {  
  633.                         return false;  
  634.                         }  
  635.                         }  
  636.      
  637.                         function autoReplace($table, $field_values, $update_values, $where = '', $querymode = '')  
  638.                         {  
  639.                                 $field_descs = $this->getAll('DESC ' . $table);  
  640.      
  641.                                         $primary_keys = array();  
  642.                                 foreach ($field_descs AS $value)  
  643.                                 {  
  644.                                 $field_names[] = $value['Field'];  
  645.                                     if ($value['Key'] == 'PRI')  
  646.                                         {  
  647.                                         $primary_keys[] = $value['Field'];  
  648.                                 }  
  649.                                 }  
  650.      
  651.                                 $fields = $values = array();  
  652.                                 foreach ($field_names AS $value)  
  653.                                 {  
  654.                                 if (array_key_exists($value, $field_values) == true)  
  655.                                 {  
  656.                                     $fields[] = $value;  
  657.                                     $values[] = "'" . $field_values[$value] . "'";  
  658.                                 }  
  659.                                     }  
  660.      
  661.                                     $sets = array();  
  662.                                     foreach ($update_values AS $key => $value)  
  663.                                         {  
  664.                                             if (array_key_exists($key, $field_values) == true)  
  665.                                             {  
  666.                                             if (is_int($value) || is_float($value))  
  667.                 {  
  668.                 $sets[] = $key . ' = ' . $key . ' + ' . $value;  
  669.                 }  
  670.                 else  
  671.                 {  
  672.                 $sets[] = $key . " = '" . $value . "'";  
  673.     }  
  674.     }  
  675.     }  
  676.      
  677.     $sql = '';  
  678.     if (empty($primary_keys))  
  679.     {  
  680.     if (!empty($fields))  
  681.     {  
  682.     $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';  
  683.     }  
  684.     }  
  685.     else  
  686.     {  
  687.     if ($this->version() >= '4.1')  
  688.     {  
  689.     if (!empty($fields))  
  690.     {  
  691.         $sql = 'INSERT INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';  
  692.         if (!empty($sets))  
  693.                 {  
  694.                 $sql .=  'ON DUPLICATE KEY UPDATE ' . implode(', ', $sets);  
  695.         }  
  696.         }  
  697.         }  
  698.         else  
  699.         {  
  700.             if (empty($where))  
  701.             {  
  702.                 $where = array();  
  703.                 foreach ($primary_keys AS $value)  
  704.                 {  
  705.                 if (is_numeric($value))  
  706.                 {  
  707.                         $where[] = $value . ' = ' . $field_values[$value];  
  708.                 }  
  709.                 else  
  710.                 {  
  711.                 $where[] = $value . " = '" . $field_values[$value] . "'";  
  712.                 }  
  713.                 }  
  714.                 $where = implode(' AND ', $where);  
  715.     }  
  716.      
  717.                 if ($where && (!empty($sets) || !empty($fields)))  
  718.                 {  
  719.                 if (intval($this->getOne("SELECT COUNT(*) FROM $table WHERE $where")) > 0)  
  720.                 {  
  721.                 if (!empty($sets))  
  722.                 {  
  723.                 $sql = 'UPDATE ' . $table . ' SET ' . implode(', ', $sets) . ' WHERE ' . $where;  
  724.                 }  
  725.                 }  
  726.                 else  
  727.                 {  
  728.                 if (!empty($fields))  
  729.                 {  
  730.                     $sql = 'REPLACE INTO ' . $table . ' (' . implode(', ', $fields) . ') VALUES (' . implode(', ', $values) . ')';  
  731.                 }  
  732.                 }  
  733.                 }  
  734.                 }  
  735.                 }  
  736.      
  737.                 if ($sql)  
  738.                 {  
  739.                 return $this->query($sql, $querymode);  
  740.                 }  
  741.                 else  
  742.                 {  
  743.                     return false;  
  744.                 }  
  745.                 }  
  746.      
  747.                 function setMaxCacheTime($second)  
  748.                 {  
  749.                 $this->max_cache_time = $second;  
  750.                 }  
  751.      
  752.                 function getMaxCacheTime()  
  753.                 {  
  754.                     return $this->max_cache_time;  
  755.                     }  
  756.      
  757.                     function getSqlCacheData($sql, $cached = '')  
  758.                     {  
  759.                     $sql = trim($sql);  
  760.      
  761.                     $result = array();  
  762.                     $result['filename'] = $this->root_path . $this->cache_data_dir . 'sqlcache_' . abs(crc32($this->dbhash . $sql)) . '_' . md5($this->dbhash . $sql) . '.php';  
  763.      
  764.                     $result['data'] = $GLOBALS['cache']->get($result['filename']);  
  765.                     if($result['data']===false)  
  766.                     {  
  767.                     $result['storecache'] = true;  
  768.                     }  
  769.                     else  
  770.                     {  
  771.                     $result['storecache'] = false;  
  772.                     }  
  773.                     return $result;  
  774.                     }  
  775.      
  776.                     function setSqlCacheData($result, $data)  
  777.                     {  
  778.                             if ($result['storecache'] === true && $result['filename'])  
  779.                             {  
  780.                             $GLOBALS['cache']->set($result['filename'],$data,$this->max_cache_time);  
  781.                     }  
  782.                     }  
  783.      
  784.                     /* 获取 SQL 语句中最后更新的表的时间,有多个表的情况下,返回最新的表的时间 */  
  785.                     function table_lastupdate($tables)  
  786.                     {  
  787.                     if ($this->link_id === NULL)  
  788.                     {  
  789.                         $this->connect($this->settings['dbhost'], $this->settings['dbuser'], $this->settings['dbpw'], $this->settings['dbname'], $this->settings['charset'], $this->settings['pconnect']);  
  790.                         $this->settings = array();  
  791.                     }  
  792.      
  793.                     $lastupdatetime = '0000-00-00 00:00:00';  
  794.      
  795.                     $tables = str_replace('`', '', $tables);  
  796.                     $this->mysql_disable_cache_tables = str_replace('`', '', $this->mysql_disable_cache_tables);  
  797.      
  798.                     foreach ($tables AS $table)  
  799.                             {  
  800.                                 if (in_array($table, $this->mysql_disable_cache_tables) == true)  
  801.                                 {  
  802.                                 $lastupdatetime = '2037-12-31 23:59:59';  
  803.      
  804.                                 break;  
  805.                             }  
  806.      
  807.                             if (strstr($table, '.') != NULL)  
  808.                             {  
  809.    $tmp = explode('.', $table);  
  810.    $sql = 'SHOW TABLE STATUS FROM `' . trim($tmp[0]) . "` LIKE '" . trim($tmp[1]) . "'";  
  811.    }  
  812.    else  
  813.    {  
  814.    $sql = "SHOW TABLE STATUS LIKE '" . trim($table) . "'";  
  815.    }  
  816.    $result = mysql_query($sql, $this->link_id);  
  817.      
  818.    $row = mysql_fetch_assoc($result);  
  819.    if ($row['Update_time'] > $lastupdatetime)  
  820.    {  
  821.    $lastupdatetime = $row['Update_time'];  
  822.    }  
  823.    }  
  824.    $lastupdatetime = strtotime($lastupdatetime) - $this->timezone + $this->timeline;  
  825.      
  826.    return $lastupdatetime;  
  827.    }  
  828.      
  829.    function get_table_name($query_item)  
  830.    {  
  831.    $query_item = trim($query_item);  
  832.    $table_names = array();  
  833.      
  834.    /* 判断语句中是不是含有 JOIN */  
  835.    if (stristr($query_item, ' JOIN ') == '')  
  836.    {  
  837.    /* 解析一般的 SELECT FROM 语句 */  
  838.    if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?(?:\s*,\s*(?:`?\w+`?\s*\.\s*)?`?\w+`?(?:(?:\s*AS)?\s*`?\w+`?)?)*)/is', $query_item, $table_names))  
  839.    {  
  840.    $table_names = preg_replace('/((?:`?\w+`?\s*\.\s*)?`?\w+`?)[^,]*/', '\1', $table_names[1]);  
  841.      
  842.    return preg_split('/\s*,\s*/', $table_names);  
  843.    }  
  844.    }  
  845.    else  
  846.    {  
  847.    /* 对含有 JOIN 的语句进行解析 */  
  848.    if (preg_match('/^SELECT.*?FROM\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)(?:(?:\s*AS)?\s*`?\w+`?)?.*?JOIN.*$/is', $query_item, $table_names))  
  849.    {  
  850.    $other_table_names = array();  
  851.    preg_match_all('/JOIN\s*((?:`?\w+`?\s*\.\s*)?`?\w+`?)\s*/i', $query_item, $other_table_names);  
  852.      
  853.    return array_merge(array($table_names[1]), $other_table_names[1]);  
  854.    }  
  855.    }  
  856.      
  857.    return $table_names;  
  858.    }  
  859.      
  860.    /* 设置不允许进行缓存的表 */  
  861.    function set_disable_cache_tables($tables)  
  862.    {  
  863.    if (!is_array($tables))  
  864.    {  
  865.    $tables = explode(',', $tables);  
  866.    }  
  867.      
  868.    foreach ($tables AS $table)  
  869.    {  
  870.    $this->mysql_disable_cache_tables[] = $table;  
  871.    }  
  872.      
  873.    array_unique($this->mysql_disable_cache_tables);  
  874.    }  
  875.    }  
  876.   
  877. ?>  

 


至此框架搭建完成,下面来写一个简单的例子

三.介绍简单的实例

controller控制层文件./app/controllers/user.php用户类

 

[php] view plain copy
 
    1. <?php  
    2. /** 
    3.  * @file: user.php 用户控制层 
    4.  * @version: 1.0 
    5.  * @author: Sara 
    6.  * @create: 2012-12-17 10:15:00 
    7.  * @update: 2012-12-17 10:15:00 
    8.  * @access: <a target="_blank" href="http://blog.csdn.net/haiqiao_2010" style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">http://blog.csdn.net/haiqiao_2010</a> 
    9.  * @copyright: 2012 <a target="_blank" href="http://blog.csdn.net/haiqiao_2010" style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">http://blog.csdn.net/haiqiao_2010</a> All rights reserved. 
    10.  **/  
    11. header('Content-Type: text/html; charset=utf-8');  
    12. @require_once './core/config/conn.php';  
    13. class user  
    14. {  
    15. /* 
    16.      * method __construct 
    17.     * paramemter string $a 
    18.     * return 提示信息/调用方法 
    19.     */  
    20.     function __construct()  
    21.     {  
    22.         $action=@trim(@$_REQUEST['act']);  
    23.         if(empty($action)){  
    24.             $action="index";  
    25.         }else{  
    26.             if(!in_array($action,array('index','login','register','<span style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">userUpdatePwd</span><span style="font-family:verdana,'ms song',宋体,Arial,微软雅黑,Helvetica,sans-serif">'))){</span>  
    27.                 ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>$action));  
    28.             }  
    29.         }  
    30.           
    31.     }  
    32.       
    33.     /* 
    34.      * method index 非法调用 
    35.     * param 
    36.     * return 
    37.     */  
    38.     public function index()  
    39.     {  
    40.         ajax_return(array('recode'=>"0003",'msg'=>"非法操作",'data'=>@$_REQUEST['act']));  
    41.     }  
    42.       
    43.     /* 
    44.      * method login 用户登陆(支持邮箱+密码或者账号+密码) 
    45.     * param string $user_name,string $user_pwd,string $l_ip,string $city_name,float $l_xpoint,float $l_ypoint 
    46.     * return 返回成功/失败已经登陆信息 
    47.     */  
    48.     public function login()  
    49.     {  
    50.         $data=json_decode(@$_REQUEST['req']);  
    51.         $user_name_or_email = trim(new_htmlspecialchars(new_addslashes(@$data->user_name)));  
    52.         $user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd)));  
    53.         $log['l_ip'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ip)));  
    54.         $log['city_name'] = trim(new_htmlspecialchars(new_addslashes(@$data->city_name)));  
    55.         $log['l_xpoint'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_xpoint)));  
    56.         $log['l_ypoint'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_ypoint)));  
    57.         $log['l_type'] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android  
    58.         $log['l_version'] = trim(new_htmlspecialchars(new_addslashes(@$data->l_version)));  
    59.           
    60.         if(empty($user_name_or_email)|| empty($user_pwd))  
    61.         {  
    62.             $r=array('recode'=>"0002",'msg'=>"参数错误",'data'=>'');  
    63.         }  
    64.         else  
    65.         {  
    66.             $user_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user where (user_name='".$user_name_or_email."' or email = '".$user_name_or_email."') and is_delete = 0");  
    67.             if(!$user_data)  
    68.             {  
    69.                 $r=array('recode'=>"1014",'msg'=>"该用户不存在,请确认操作.",'data'=>'');  
    70.             }  
    71.             else  
    72.             {  
    73.                 if($user_data['user_pwd'] != md5($user_pwd.$user_data['code'])&&$user_data['user_pwd']!=$user_pwd)  
    74.                 {  
    75.                     $r=array('recode'=>"0012",'msg'=>"用户密码不对,请确认您的登陆信息.",'data'=>'');  
    76.                 }  
    77.                 elseif($user_data['is_effect'] != 1)  
    78.                 {  
    79.                     $r=array('recode'=>"0011",'msg'=>"账号未被激活,暂时不能进行如下操作.",'data'=>'');  
    80.                 }  
    81.                 elseif($user_data['is_locking'] != 0)  
    82.                 {  
    83.                     $r=array('recode'=>"0014",'msg'=>"账号已经被锁定,暂时不能进行如下操作.",'data'=>'');  
    84.                     if(app_conf("SHOP_TEL")!='')  
    85.                         $r['msg'].="若有疑问,请致电联系客服: <".app_conf("SHOP_TEL").">";  
    86.                 }  
    87.                 else  
    88.                 {  
    89.                     //im:查看会员分组是否能够升级  
    90.                     $user_current_group = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_group where id = ".intval($user_data['group_id']));  
    91.                     $user_group = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_group where score <=".intval($user_data['score'])." order by score desc");  
    92.                     if($user_current_group['score']<$user_group['score'])  
    93.                     {  
    94.                         $user_data['group_id'] = intval($user_group['id']);  
    95.                         $GLOBALS['db']->query("update ".DB_PREFIX."user set group_id = ".$user_data['group_id']." where id = ".$user_data['id']);  
    96.                         $pm_title = "您已经成为".$user_group['name']."";  
    97.                         $pm_content = "恭喜您,您已经成为".$user_group['name']."。";  
    98.                         if($user_group['discount']<1)  
    99.                         {  
    100.                             $pm_content.="您将享有".($user_group['discount']*10)."折的购物优惠";  
    101.                         }  
    102.                         send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true);  
    103.                     }  
    104.                     //im:查看会员积分是否能够升级  
    105.                     $user_current_level = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_level where id = ".intval($user_data['level_id']));  
    106.                     $user_level = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user_level where point <=".intval($user_data['point'])." order by point desc");  
    107.                     if($user_current_level['point']<$user_level['point'])  
    108.                     {  
    109.                         $user_data['level_id'] = intval($user_level['id']);  
    110.                         $GLOBALS['db']->query("update ".DB_PREFIX."user set level_id = ".$user_data['level_id']." where id = ".$user_data['id']);  
    111.                         $pm_title = "您已经成为".$user_level['name']."";  
    112.                         $pm_content = "恭喜您,您已经成为".$user_level['name']."。";  
    113.                         send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true);  
    114.                     }  
    115.                       
    116.                     if($user_current_level['point']>$user_level['point'])  
    117.                     {  
    118.                         $user_data['level_id'] = intval($user_level['id']);  
    119.                         $GLOBALS['db']->query("update ".DB_PREFIX."user set level_id = ".$user_data['level_id']." where id = ".$user_data['id']);  
    120.                         $pm_title = "您已经降为".$user_level['name']."";  
    121.                         $pm_content = "很报歉,您已经降为".$user_level['name']."。";  
    122.                         send_user_msg($pm_title,$pm_content,0,$user_data['id'],get_gmtime(),0,true,true);  
    123.                     }  
    124.                     $log['l_time']=get_gmtime();  
    125.                     $log['user_id']=$user_data['id'];  
    126.                     //im:更新最后登陆信息  
    127.                     $GLOBALS['db']->query("update ".DB_PREFIX."user set login_ip = '".$log['l_ip']."',login_time= ".$log['l_time'].",group_id=".intval($user_data['group_id'])." where id =".$user_data['id']);  
    128.                       
    129.                     //添加登陆日志  
    130.                     $GLOBALS['db']->autoExecute("im_user_login_log",$log);  
    131.                       
    132.                     //检查是否为最新系统版本  
    133.                     $log['l_type'] = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android  
    134.                     switch ($log['l_type'])//im_m_package:p_type:手机系统版本类型,默认为0 ios系统;为1 android系统  
    135.                     {  
    136.                         case "1":  
    137.                             $package=$GLOBALS['db']->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=0");  
    138.                             break;  
    139.                         case "2":  
    140.                             $package=$GLOBALS['db']->getRow("select p_version,p_url,is_must from im_m_package where is_effect=1 and p_type=1");  
    141.                             break;  
    142.                         default:  
    143.                             break;  
    144.                     }  
    145.                     if (@$package && strnatcmp($log['l_version'],$package['p_version'])<0)  
    146.                     {  
    147. //                      $varreg="/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/";  
    148.                         $varreg="/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";  
    149.                         if(!preg_match($varreg,$package['p_url']))//im:判断是否为超链接  
    150.                         {  
    151.                             $package['p_url']=URL_PATH.str_replace("./","",$package['p_url']);  
    152.                         }  
    153.   
    154.                         $r=array('recode'=>"0015",'msg'=>"用户登陆成功.",'data'=>array('user_id'=>$user_data['id'],'user_name'=>$user_data['user_name'],'true_name'=>$user_data['true_name'],'email'=>is_null($user_data['email'])?"":$user_data['email'],'mobile'=>is_null($user_data['mobile'])?"":$user_data['mobile'],'l_time'=>to_date($log['l_time']),'p_version'=>$package['p_version'],'p_url'=>$package['p_url'],'is_must'=>$package['is_must']));  
    155.                       
    156.                     }  
    157.                     else  
    158.                     {  
    159.                         $r=array('recode'=>"0015",'msg'=>"用户登陆成功.",'data'=>array('user_id'=>$user_data['id'],'user_name'=>$user_data['user_name'],'true_name'=>$user_data['true_name'],'email'=>is_null($user_data['email'])?"":$user_data['email'],'mobile'=>is_null($user_data['mobile'])?"":$user_data['mobile'],'l_time'=>to_date($log['l_time']),'p_version'=>$log['l_version'],'p_url'=>"",'is_must'=>""));  
    160.                     }  
    161.                 }  
    162.             }  
    163.         }  
    164.         ajax_return($r);  
    165.     }  
    166.       
    167.     /* 
    168.      * method register 用户注册 
    169.     * param int $type,string $user_name,string $user_pwd,string $email ,string mobile 
    170.     * return 返回成功/失败 
    171.     */  
    172.     public function register()  
    173.     {  
    174.         //{"type":0,"user_name":"sara123","user_pwd":"123456","email":"sara123@qq.com","mobile":"13245678900","xpoint":"119.306938","ypoint":"26.069746","city_name":"\u5b81\u590f","ip":"192.168.1","l_type":"1","l_version":"1.0","verify_code":"123456","msg_id":"12"}  
    175. //      $data=json_encode(array(  
    176. //                      "type"=>0,  
    177. //                      "user_name"=>"sara123",  
    178. //                      "user_pwd"=>"123456",  
    179. //                      "email"=>"sara123@qq.com",  
    180. //                      "mobile"=>"13245678900",  
    181. //                      "xpoint"=>"119.306938",  
    182. //                      "ypoint"=>"26.069746",  
    183. //                      "city_name"=>"宁夏",  
    184. //                      "ip"=>"192.168.1",  
    185. //                      "l_type"=>"1",  
    186. //                      "l_version"=>"1.0",  
    187. //                      "verify_code"=>"123456",  
    188. //                      "msg_id"=>12  
    189. //                      ));  
    190.         $data=json_decode(@$_REQUEST['req']);  
    191.         $type = intval(@$data->type);//im:注册方式:默认为0:邮箱+账号;1为:手机号+账号  
    192.   
    193.         $user_data['user_name'] = strtolower(trim(new_htmlspecialchars(new_addslashes(@$data->user_name))));  
    194.         $user_data["user_pwd"] = trim(new_htmlspecialchars(new_addslashes(@$data->user_pwd)));  
    195.         $user_data["email"] = trim(new_htmlspecialchars(new_addslashes(@$data->email)));  
    196.         $user_data["mobile"] = trim(new_htmlspecialchars(new_addslashes(@$data->mobile)));  
    197.         $user_data["xpoint"] = doubleval(@$data->xpoint);  
    198.         $user_data["ypoint"] = doubleval(@$data->ypoint);  
    199.         $city_name = trim(new_htmlspecialchars(new_addslashes(@$data->city_name)));  
    200.         $user_data["login_ip"] = trim(new_htmlspecialchars(new_addslashes(@$data->ip)));  
    201.         $l_type = intval(@$data->l_type);//用户登陆类型:默认为0,网站登陆,1为手机端IOS登陆,2为手机端android  
    202.         $l_version = trim(new_htmlspecialchars(new_addslashes(@$data->l_version)));  
    203.   
    204.         if($user_data['user_name']==''|| !preg_match("/^[a-z\d]{3,20}$/i", $user_data['user_name']))  
    205.         {  
    206.             ajax_return(array('recode'=>"1001",'msg'=>"用户名不能为空,且为3-20个由字母和数字组成的字符串.".$data->user_name,'data'=>""));  
    207.         }  
    208.         else  
    209.         {  
    210.             if($GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where user_name = '".trim($user_data['user_name'])."'")>0)  
    211.             {  
    212.                 ajax_return(array('recode'=>"1006",'msg'=>"该用户名已经存在,请重新填写",'data'=>''));  
    213.             }  
    214.             else   
    215.             {  
    216.                 $msg=get_pwd_strength($user_data['user_pwd']);  
    217.                 if(!empty($msg))  
    218.                 {  
    219.                     ajax_return(array('recode'=>"1003",'msg'=>$msg,'data'=>''));  
    220.                       
    221.                 }  
    222.                 else  
    223.                 {  
    224.                     if($type==0)  
    225.                     {  
    226.                         if(!check_email($user_data['email']))  
    227.                         {  
    228.                             ajax_return(array('recode'=>"1003",'msg'=>"邮箱格式不正确.",'data'=>''));  
    229.                         }  
    230.                         else  
    231.                         {  
    232.                             if($GLOBALS['db']->getOne("select count(*) from ".DB_PREFIX."user where email = '".trim($user_data['email'])."'")>0)  
    233.                             {  
    234.                                 ajax_return(array('recode'=>"1004",'msg'=>"该邮箱已经被注册过,请填写其他邮箱.",'data'=>''));  
    235.                             }  
    236.                         }  
    237.                     }  
    238.                     else  
    239.                     {  
    240.                         if(!check_mobile($user_data['mobile']))  
    241.                         {  
    242.                             ajax_return(array('recode'=>"1005",'msg'=>"手机号码格式错误,手机号码为11位.",'data'=>''));  
    243.                         }  
    244.                         else  
    245.                         {  
    246.                             $verify_code = trim(new_htmlspecialchars(new_addslashes(@$data->verify_code)));  
    247.                             $msg_id = intval(@$data->msg_id);  
    248.                             if ($msg_id<=0 || empty($verify_code))  
    249.                             {  
    250.                                 ajax_return(array('recode'=>"0002",'msg'=>"参数错误",'data'=>''));  
    251.                             }  
    252.                             $verify_result=use_sms_code(0,0,$msg_id,0,$user_data["mobile"],$verify_code);  
    253.                             if($verify_result['status']==0)  
    254.                             {  
    255.                                 ajax_return(array('recode'=>$verify_result['recode'],'msg'=>$verify_result['msg'],'data'=>''));  
    256.                             }  
    257.                         }  
    258.                     }  
    259.                         //验证结束开始插入数据  
    260.                         $user_data['create_time'] = get_gmtime();  
    261.                         $user_data['update_time'] = get_gmtime();  
    262.                           
    263.                         //获取默认会员组, 即升级积分最小的会员组  
    264.                         $user_data['group_id'] = $GLOBALS['db']->getOne("select id from ".DB_PREFIX."user_group order by score asc limit 1");  
    265.                         //获取用户所在城市id  
    266.                         $city = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."region_conf where name='".$city_name."'");  
    267.                         if ($city)  
    268.                         {  
    269.                             switch ($city['region_level']) {//im:1:国 2:省 3:市(县) 4:区(镇)  
    270.                                 case "2":  
    271.                                     $user_data['province_id']=$city['id'];  
    272.                                     break;  
    273.                                 case "3":  
    274.                                     $user_data['city_id']=$city['id'];  
    275.                                     $user_data['province_id'] = $city['pid'];  
    276.                                     break;  
    277.                                 default:  
    278.                                     break;  
    279.                             }  
    280.                         }  
    281.                         //账号是否激活  
    282. //                      $user_data['is_effect'] = empty($user_data['is_effect'])? app_conf("USER_VERIFY"):$user_data['is_effect'];  
    283.                         $user_data['is_effect']=1;//手机端注册,默认账号为激活状态  
    284.                         $user_data['code'] = ''; //默认不使用code, 该值用于其他系统导入时的初次认证  
    285.                         $user_data['user_pwd'] = md5($user_data['user_pwd'].$user_data['code']);  
    286.                         $user_data['register_type'] = 1;//register_type:im:用户注册的方式:默认为0,web端注册,1为手机端注册  
    287.                           
    288.                         if($GLOBALS['db']->autoExecute(DB_PREFIX."user",$user_data,"INSERT"))  
    289.                         {  
    290.                             $user_id = $GLOBALS['db']->insert_id();  
    291.                             $register_money = app_conf('USER_REGISTER_MONEY');  
    292.                             $register_score = app_conf('USER_REGISTER_SCORE');  
    293.                             $register_point = app_conf('USER_REGISTER_POINT');  
    294.                               
    295.                             if($register_money>0||$register_score>0)  
    296.                             {  
    297.                                 $user_get['score'] = $register_score;  
    298.                                 $user_get['money'] = $register_money;  
    299.                                 $user_get['point'] = $register_point;  
    300.                                 @require_once './app/modules/userModule.php';  
    301.                                 modify_account($user_get,intval($user_id),"在".to_date(get_gmtime())."注册成功");  
    302.                             }  
    303.                               
    304.                             //im:添加登陆日志  
    305.                             $GLOBALS['db']->autoExecute("im_user_login_log",array('user_id'=>$user_id,'l_type'=>1,'l_ip'=>$user_data['login_ip'],'l_time'=>get_gmtime(),"city_name"=>$city_name,"l_xpoint"=>$user_data['xpoint'],"l_ypoint"=>$user_data['ypoint'],"l_type"=>$l_type,"l_version"=>$l_version));  
    306.                               
    307.                             ajax_return(array('recode'=>"1009",'msg'=>"用户注册成功",'data'=>array('user_id'=>$user_id,"user_name"=>$user_data['user_name'],"email"=>is_null($user_data['email'])?"":$user_data['email'],"mobile"=>is_null($user_data['mobile'])?"":$user_data['mobile'],"create_time"=>to_date($user_data['create_time']))));  
    308.                         }  
    309.                         else  
    310.                         {  
    311.                             ajax_return(array('recode'=>"1008",'msg'=>"用户注册失败",'data'=>''));  
    312.                         }  
    313.                 }  
    314.             }  
    315.         }  
    316.     }  
    317.       
    318.     /* 
    319.      * method userUpdatePwd 修改密码接口 
    320.     * parameter int $user_id 
    321.     * parameter string $old_pwd 
    322.     * parameter string $new_pwd 
    323.     * return 返回成功/失败 
    324.     */  
    325.     function userUpdatePwd()  
    326.     {  
    327.         //{"user_id":0,"old_pwd":"111@qq.com","new_pwd":"13245678900"}  
    328.         //      $data=json_encode(array(  
    329.         //                      "user_id"=>0,  
    330.         //                      "old_pwd"=>"sara123@qq.com",  
    331.         //                      "new_pwd"=>"13245678900"  
    332.         //                      ));  
    333.         $data=json_decode(@$_REQUEST['req']);  
    334.         $user_id = intval(@$data->user_id);  
    335.         $user_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->old_pwd)));  
    336.         $new_pwd = trim(new_htmlspecialchars(new_addslashes(@$data->new_pwd)));  
    337.           
    338.         if ($user_id<=0)  
    339.         {  
    340.             $r=array('recode'=>"0002",'msg'=>"参数错误.",'data'=>'');  
    341.         }  
    342.         else  
    343.         {  
    344.             $msg=get_pwd_strength($new_pwd);  
    345.             if(!empty($msg))  
    346.             {  
    347.                 $r=array('recode'=>"1002",'msg'=>$msg,'data'=>'');  
    348.                 ajax_return($r);  
    349.             }  
    350.             else  
    351.             {  
    352.                 $user_data = $GLOBALS['db']->getRow("select * from ".DB_PREFIX."user where id='".$user_id."'");  
    353.                 if(!$user_data)  
    354.                 {  
    355.                     $r=array('recode'=>"1014",'msg'=>"该用户不存在,请确认操作.",'data'=>'');  
    356.                 }  
    357.                 else  
    358.                 {  
    359.                     if($user_data['user_pwd'] != md5($user_pwd.$user_data['code'])&&$user_data['user_pwd']!=$user_pwd)  
    360.                     {  
    361.                         $r=array('recode'=>"0012",'msg'=>"用户密码不对,请确认您的登陆信息.",'data'=>'');  
    362.                     }  
    363.                     elseif($user_data['is_effect'] != 1)  
    364.                     {  
    365.                         $r=array('recode'=>"0011",'msg'=>"账号未被激活,暂时不能进行如下操作.",'data'=>'');  
    366.                     }  
    367.                     else if ($user_data['is_delete']==1)  
    368.                     {  
    369.                         $r=array('recode'=>"1012",'msg'=>"该用户已被删除,请重新注册.",'data'=>'');  
    370.                     }  
    371.                     else  
    372.                     {  
    373.                         $user_data['user_pwd'] = $new_pwd;  
    374.                         $new_pwd = md5($new_pwd.$user_data['code']);  
    375.                         if($GLOBALS['db']->query("update ".DB_PREFIX."user set user_pwd = '".$new_pwd."',password_verify='' where id = ".$user_data['id'] ))  
    376.                         {  
    377.                             $GLOBALS['db']->query("update ".DB_PREFIX."supplier_account set account_password = '".$new_pwd."' where user_id = ".$user_data['id'] );  
    378.                             $r=array('recode'=>"0000",'msg'=>"操作成功.",'data'=>'');  
    379.                         }  
    380.                         else  
    381.                         {  
    382.                             $r=array('recode'=>"0001",'msg'=>"操作失败.",'data'=>'');  
    383.                         }  
    384.                     }  
    385.                 }  
    386.             }  
    387.         }  
    388.         ajax_return($r);  
    389.     }  
    390.       
    391. }  
    392. ?> 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!