php常用的函数

Posted 6789

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php常用的函数相关的知识,希望对你有一定的参考价值。

技术分享
   1 <?php
   2     public function clear_html($array) 
   3      {
   4             if (!is_array($array))
   5                 return trim(htmlspecialchars($array, ENT_QUOTES));
   6             foreach ($array as $key => $value) {
   7                 if (is_array($value)) {
   8                     $this->clear_html($value);
   9                 } else {
  10                     $array[$key] = trim(htmlspecialchars($value, ENT_QUOTES));
  11                 }
  12             }
  13             return $array;
  14         }
  15 
  16      public function dexit($data = ‘‘) 
  17      {
  18         if (is_array($data)) {
  19             echo json_encode($data);
  20         } else {
  21             echo $data;
  22         }
  23         exit();
  24      }
  25 
  26  
  27     //二维数组转一维数组
  28     public function arr2_arr1($arrdata,$v)
  29     {
  30         $arrs = array();
  31         foreach ($arrdata as $key => $value) {
  32             $arrs[] = $value[$v];
  33         }
  34         return $arrs;
  35     }
  36     //生成php随机数
  37      public function randomkey($length)   
  38     {   
  39        $pattern = ‘1234567890abcdefghijklmnopqrstuvwxyz   
  40                    ABCDEFGHIJKLOMNOPQRSTUVWXYZ‘;  
  41         for($i=0;$i<$length;$i++)   
  42         {   
  43             $key .= $pattern{mt_rand(0,35)};    //生成php随机数   
  44         }   
  45         return $key;   
  46     }
  47     
  48     
  49     //打印
  50     public function dump($var, $echo = true, $label = null, $strict = true)
  51 {
  52     $label = ($label === null) ? ‘‘ : rtrim($label) . ‘ ‘;
  53     if (!$strict) {
  54         if (ini_get(‘html_errors‘)) {
  55             $output = print_r($var, true);
  56             $output = ‘<pre>‘ . $label . htmlspecialchars($output, ENT_QUOTES) . ‘</pre>‘;
  57         } else {
  58             $output = $label . print_r($var, true);
  59         }
  60     } else {
  61         ob_start();
  62         var_dump($var);
  63         $output = ob_get_clean();
  64         if (!extension_loaded(‘xdebug‘)) {
  65             $output = preg_replace("/\]\=\>\n(\s+)/m", ‘] => ‘, $output);
  66             $output = ‘<pre>‘ . $label . htmlspecialchars($output, ENT_QUOTES) . ‘</pre>‘;
  67         }
  68     }
  69     if ($echo) {
  70         echo($output);
  71         return null;
  72     } else
  73         return $output;
  74 }
  75 
  76  //无限极分类
  77       function GetTree($arr,$pid,$step){
  78         global $tree;
  79         foreach($arr as $key=>$val) {
  80             if($val[‘auth_pid‘] == $pid) {
  81                 $flg = str_repeat(‘└―‘,$step);
  82                 $val[‘name‘] = $flg.$val[‘name‘];
  83                 $tree[] = $val;
  84                 GetTree($arr , $val[‘id‘] ,$step+1);
  85             }
  86         }
  87         return $tree;
  88    }
  89     
  90 ?>
  91 
  92  <?php
  93 /**
  94  * 公共方法
  95  */
  96  
  97 
  98 /**
  99  * 去除多余的转义字符
 100  */
 101 function doStripslashes(){
 102     if(get_magic_quotes_gpc()){
 103         $_GET = stripslashesDeep($_GET);
 104         $_POST = stripslashesDeep($_POST);
 105         $_COOKIE = stripslashesDeep($_COOKIE);
 106         $_REQUEST = stripslashesDeep($_REQUEST);
 107     }
 108 }
 109 
 110 /**
 111  * 递归去除转义字符
 112  */
 113 function stripslashesDeep($value){
 114     $value = is_array($value) ? array_map(‘stripslashesDeep‘, $value) : stripslashes($value);
 115     return $value;
 116 }
 117 
 118 /**
 119  * URL重定向
 120  * @param string $url 重定向的URL地址
 121  * @param integer $time 重定向的等待时间(秒)
 122  * @param string $msg 重定向前的提示信息
 123  * @return void
 124  */
 125 function redirect($url, $time=0, $msg=‘‘){
 126     //多行URL地址支持
 127     $url        = str_replace(array("\n", "\r"), ‘‘, $url);
 128     if (empty($msg))
 129         $msg    = "系统将在{$time}秒之后自动跳转到{$url}!";
 130     if (!headers_sent()){
 131         // redirect
 132         if (0 === $time) {
 133             header(‘Location: ‘ . $url);
 134         } else {
 135             header("refresh:{$time};url={$url}");
 136             echo($msg);
 137         }
 138         exit();
 139     } else {
 140         $str    = "<meta http-equiv=‘Refresh‘ content=‘{$time};URL={$url}‘>";
 141         if ($time != 0)
 142             $str .= $msg;
 143         exit($str);
 144     }
 145 }
 146 
 147 /**
 148  * 得到网站的网址
 149  */
 150 function getWebUrl() {
 151     $phpself = isset($_SERVER[‘SCRIPT_NAME‘]) ? $_SERVER[‘SCRIPT_NAME‘] : ‘‘;
 152     if(preg_match("/^.*\//", $phpself, $matches)){
 153         return ‘http://‘ . $_SERVER[‘HTTP_HOST‘] . $matches[0];
 154     }else{
 155         return ‘‘;
 156     }
 157 }
 158 /**
 159  * 得到网址的顶级域名
 160  */
 161 function getUrlTopDomain($url){
 162     $domain_array = parse_url($url);
 163     $host = strtolower($domain_array[‘host‘]);
 164     $two_suffix = array(‘.com.cn‘,‘.gov.cn‘,‘.net.cn‘,‘.org.cn‘,‘.ac.cn‘);
 165     foreach($two_suffix as $key=>$value){
 166         preg_match(‘#(.*?)‘.$value.‘$#‘,$host,$match_arr);
 167         if(!empty($match_arr)){
 168             $match_array = $match_arr;
 169             break;
 170         }
 171     }
 172     $host_arr = explode(‘.‘,$host);
 173     if(!empty($match_array)){
 174         $host_arr_last1 = array_pop($host_arr);
 175         $host_arr_last2 = array_pop($host_arr);
 176         $host_arr_last3 = array_pop($host_arr);
 177         
 178         return $host_arr_last3.‘.‘.$host_arr_last2.‘.‘.$host_arr_last1;
 179     }else{
 180         $host_arr_last1 = array_pop($host_arr);
 181         $host_arr_last2 = array_pop($host_arr);
 182         return $host_arr_last2.‘.‘.$host_arr_last1;
 183     }
 184 }
 185 /**
 186  * 得到网址的域名
 187  */
 188 function getUrlDomain($url){
 189     $domain_array = parse_url($url);
 190     $host = strtolower($domain_array[‘host‘]);
 191     return $host;
 192 }
 193 
 194 /**
 195  * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
 196  * @param string $name 缓存名称
 197  * @param mixed $value 缓存值
 198  * @param string $path 缓存路径
 199  * @return mixed
 200  */
 201 function F($name, $value=‘‘, $path = DATA_PATH){
 202     static $_cache  = array();
 203     $filename       = $path . $name . ‘.php‘;
 204     if (‘‘ !== $value) {
 205         if (is_null($value)) {
 206             // 删除缓存
 207             return false !== strpos($name,‘*‘)?array_map("unlink", glob($filename)):unlink($filename);
 208         } else {
 209             // 缓存数据
 210             $dir            =   dirname($filename);
 211             // 目录不存在则创建
 212             if (!is_dir($dir))
 213                 mkdir($dir,0755,true);
 214             $_cache[$name]  =   $value;
 215             return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($value, true) . ";?>"));
 216         }
 217     }
 218     if (isset($_cache[$name]))
 219         return $_cache[$name];
 220     // 获取缓存数据
 221     if (is_file($filename)) {
 222         $value          =   include $filename;
 223         $_cache[$name]  =   $value;
 224     } else {
 225         $value          =   false;
 226     }
 227     return $value;
 228 }
 229 
 230 /**
 231  * 快速哈希文件数据读取和保存 针对简单类型数据 字符串、数组
 232  * @param string $name 缓存名称
 233  * @param mixed $value 缓存值
 234  * @param mixed $level 缓存的目录数
 235  * @param string $path 缓存路径
 236  * @return mixed
 237  */
 238 function S($name, $value=‘‘,$time=0,$level=2,$path=CACHE_PATH){
 239     static $_scache  = array();
 240     $name = md5($name);
 241     $haxi_dir = ‘‘;
 242     for($i=0;$i<$level;$i++){
 243         $haxi_dir .= $name[$i].‘/‘;
 244     }
 245     $filename = $path . $haxi_dir . $name . ‘.php‘;
 246     
 247     if (‘‘ !== $value) {
 248         if (is_null($value)){
 249             // 删除缓存
 250             return false !== strpos($name,‘*‘) ? array_map("unlink",glob($filename)) : unlink($filename);
 251         } else {
 252             // 缓存数据
 253             $dir  =  dirname($filename);
 254             
 255             // 目录不存在则创建
 256             if (!is_dir($dir))
 257                 mkdir($dir,0755,true);
 258             
 259             $save_file[‘content‘] = $value;
 260             if($time > 0){
 261                 $save_file[‘expire_time‘] = $_SERVER[‘REQUEST_TIME‘] + $time;
 262             }
 263             $_scache[$name]  =   $value;
 264             return file_put_contents($filename, strip_whitespace("<?php\treturn " . var_export($save_file, true) . ";?>"));
 265         }
 266     }
 267     if (isset($_scache[$name]))
 268         return $_scache[$name];
 269     // 获取缓存数据
 270     if (is_file($filename)) {
 271         $value          =   include $filename;
 272         if(!empty($value[‘expire_time‘]) && $value[‘expire_time‘]<$_SERVER[‘REQUEST_TIME‘]){
 273             strpos($name,‘*‘) ? array_map("unlink",glob($filename)) : unlink($filename);
 274              $return = false;
 275         }
 276         $return = $value[‘content‘];
 277         $_scache[$name]  =   $return;
 278     } else {
 279         $return = false;
 280     }
 281     return $return;
 282 }
 283 
 284 /**
 285  * 去除代码中的空白和注释
 286  * @param string $content 代码内容
 287  * @return string
 288  */
 289 function strip_whitespace($content){
 290     $stripStr   = ‘‘;
 291     //分析php源码
 292     $tokens     = token_get_all($content);
 293     $last_space = false;
 294     for ($i = 0, $j = count($tokens); $i < $j; $i++) {
 295         if (is_string($tokens[$i])) {
 296             $last_space = false;
 297             $stripStr  .= $tokens[$i];
 298         } else {
 299             switch ($tokens[$i][0]) {
 300                 //过滤各种PHP注释
 301                 case T_COMMENT:
 302                 case T_DOC_COMMENT:
 303                     break;
 304                 //过滤空格
 305                 case T_WHITESPACE:
 306                     if (!$last_space) {
 307                         $stripStr  .= ‘ ‘;
 308                         $last_space = true;
 309                     }
 310                     break;
 311                 case T_START_HEREDOC:
 312                     $stripStr .= "<<<THINK\n";
 313                     break;
 314                 case T_END_HEREDOC:
 315                     $stripStr .= "THINK;\n";
 316                     for($k = $i+1; $k < $j; $k++) {
 317                         if(is_string($tokens[$k]) && $tokens[$k] == ‘;‘) {
 318                             $i = $k;
 319                             break;
 320                         } else if($tokens[$k][0] == T_CLOSE_TAG) {
 321                             break;
 322                         }
 323                     }
 324                     break;
 325                 default:
 326                     $last_space = false;
 327                     $stripStr  .= $tokens[$i][1];
 328             }
 329         }
 330     }
 331     return $stripStr;
 332 }
 333 
 334 /**
 335  * 自动加载
 336  */
 337 function __autoload($class){
 338     if(file_exists(PIGCMS_PATH.‘library/controller/‘.GROUP_NAME.‘/‘.$class.‘.php‘)){
 339         require_once(PIGCMS_PATH.‘library/controller/‘.GROUP_NAME.‘/‘.$class.‘.php‘);
 340         return;
 341     }else if(file_exists(PIGCMS_PATH.‘library/controller/‘.$class.‘.php‘)) {
 342         require_once(PIGCMS_PATH.‘library/controller/‘.$class.‘.php‘);
 343         return;
 344     }else if(file_exists(PIGCMS_PATH.‘library/model/‘.$class.‘.php‘)){
 345         require_once(PIGCMS_PATH.‘library/model/‘.$class.‘.php‘);
 346         return;
 347     }else if(file_exists(PIGCMS_PATH.‘library/class/‘.$class.‘.class.php‘)){
 348         require_once(PIGCMS_PATH.‘library/class/‘.$class.‘.class.php‘);
 349         return;
 350     }else if(file_exists(PIGCMS_PATH.‘source/class/‘.$class.‘.class.php‘)){
 351         require_once(PIGCMS_PATH.‘source/class/‘.$class.‘.class.php‘);
 352         return;
 353     }
 354 
 355     $class = strtolower($class);
 356     if(file_exists(PIGCMS_PATH.‘library/controller/‘.GROUP_NAME.‘/‘.$class.‘.php‘)){
 357         require_once(PIGCMS_PATH.‘library/controller/‘.GROUP_NAME.‘/‘.$class.‘.php‘);
 358     }else if(file_exists(PIGCMS_PATH.‘library/controller/‘.$class.‘.php‘)) {
 359         require_once(PIGCMS_PATH.‘library/controller/‘.$class.‘.php‘);
 360     }else if(file_exists(PIGCMS_PATH.‘library/model/‘.$class.‘.php‘)){
 361         require_once(PIGCMS_PATH.‘library/model/‘.$class.‘.php‘);
 362     }else if(file_exists(PIGCMS_PATH.‘library/class/‘.$class.‘.class.php‘)){
 363         require_once(PIGCMS_PATH.‘library/class/‘.$class.‘.class.php‘);
 364     }else if(file_exists(PIGCMS_PATH.‘source/class/‘.$class.‘.class.php‘)){
 365 
 366         require_once(PIGCMS_PATH.‘source/class/‘.$class.‘.class.php‘);
 367     }else{
 368         pigcms_tips($class . ‘ 类不存在。‘,‘none‘);
 369     }
 370 }
 371 
 372 /**
 373  * 加载文件
 374  *
 375  */
 376 function import($file){
 377     $file_arr = explode(‘.‘,$file);
 378     $file_arr_count = count($file_arr);
 379     if(class_exists($file_arr[$file_arr_count-1],false)) return false;
 380     switch($file_arr_count){
 381         case 1:
 382             if(substr($file_arr[0],0,1) == ‘@‘){
 383                 $load_file = PIGCMS_PATH.‘library/class/‘.substr($file_arr[0],1).‘.class.php‘;
 384             }else{
 385                 $load_file = PIGCMS_PATH.‘source/class/‘.$file_arr[0].‘.class.php‘;
 386             }
 387             break;
 388         case 2:
 389             if(substr($file_arr[0],0,1) == ‘@‘){
 390                 $load_file = PIGCMS_PATH.‘library/‘.substr($file_arr[0],1).‘/‘.$file_arr[1].‘.class.php‘;
 391             }else{
 392                 $load_file = PIGCMS_PATH.‘source/‘.$file_arr[0].‘/‘.$file_arr[1].‘.class.php‘;
 393             }
 394             break;
 395         case 3:
 396             $load_file = PIGCMS_PATH.$file_arr[0].‘/‘.$file_arr[1].‘/‘.$file_arr[2].‘.class.php‘;
 397             break;
 398         default:
 399             $file_data = ‘‘;
 400             foreach($file_arr as $val){
 401                 if($file_data == ‘‘){
 402                     $file_data = $val;
 403                 }else{
 404                     $file_data .= ‘/‘.$val;
 405                 }
 406             }
 407             $load_file = PIGCMS_PATH.$file_data.‘.class.php‘;
 408     }
 409     require_file($load_file);
 410 }
 411 
 412 /**
 413  * 调用数据库类
 414  */
 415 function D($table=‘‘,$other=array()){
 416     static $db_list;
 417     import(‘source.class.mysql);
 418     if(empty($other)){
 419         if (!empty($table) && isset($db_list[$table])) {
 420             return $db_list[$table];
 421         }
 422         $db = new mysql();
 423 
 424         if($table){
 425             $db_list[$table] = $db;
 426             $db->table($table);
 427         }
 428     }else{
 429         $db = new mysql($other);
 430         $db->table($table);
 431     }
 432 
 433 
 434     return $db;
 435 }
 436 
 437 /**
 438  * 引入并使用控制器的方法
 439  */
 440 function R($group,$mode,$action){
 441     $mode = strtolower($mode);
 442     $mode_file = PIGCMS_PATH.‘library/controller/‘.$group.‘/‘.$mode.‘_controller.php‘;
 443     if(file_exists($mode_file)){
 444         $mode_name = $mode.‘_controller‘;
 445         require($mode_file);
 446         if(!class_exists($mode_name)){
 447             pigcms_tips($mode_name.‘ 类不存在。‘,‘none‘);
 448         }
 449         $mode_obj = new $mode_name;
 450         if(!method_exists($mode_obj,$action)){
 451             if(method_exists($mode_obj,‘_empty‘)){
 452                 $action = ‘_empty‘;
 453             }else{
 454                 pigcms_tips($action.‘ 方法不存在。‘,‘none‘);
 455             }
 456         }
 457         $mode_obj->$action();
 458     }else if(file_exists(TPL_PATH.‘/‘.ACTION_NAME.‘.php‘)){
 459         display();
 460     }else{
 461         if(DEBUG){
 462             pigcms_tips($mode_file.‘ 控制器文件不存在。‘,‘none‘);
 463         }else{
 464             pigcms_tips($group.‘分组 控制器 ‘.$mode.‘ 文件不存在。‘,‘none‘);
 465         }
 466     }
 467 }
 468 /**
 469  * 获得系统参数
 470  */
 471 function option($name=null,$value=null){
 472     global $_G;
 473      // 无参数时获取所有
 474     if(empty($name)){
 475         return $_G;
 476     }
 477     // 优先执行设置获取或赋值
 478     if(is_string($name)){
 479         if (!strpos($name,‘.‘)) {
 480             $name = strtolower($name);
 481             if (is_null($value))
 482                 return isset($_G[$name]) ? $_G[$name] : null;
 483             $_G[$name] = $value;
 484             return;
 485         }
 486         // 二维数组设置和获取支持
 487         $name = explode(‘.‘, $name);
 488         $name[0]   =  strtolower($name[0]);
 489         if (is_null($value))
 490             return isset($_G[$name[0]][$name[1]]) ? $_G[$name[0]][$name[1]] : null;
 491         $_G[$name[0]][$name[1]] = $value;
 492         return;
 493     }
 494     return null; // 避免非法参数
 495 }
 496 /**
 497  * 引入并实例化MODEL类
 498  */
 499 function M($model){
 500     $lower_model = strtolower($model);
 501     $model_file = PIGCMS_PATH.‘library/model/‘.$lower_model.‘_model.php‘;
 502     if(file_exists($model_file)){
 503         $model_name = $lower_model.‘_model‘;
 504         if(!class_exists($model_name,false)){
 505             require($model_file);
 506             if(!class_exists($model_name)){
 507                 pigcms_tips($model_name.‘ 类不存在。‘,‘none‘);
 508             }
 509         }
 510         $model_obj = new $model_name($model);
 511         return $model_obj;
 512     }else{
 513           $model_file = PIGCMS_PATH.‘source/plugins/bonus/model/‘.$lower_model.‘_model.php‘;
 514           if (file_exists($model_file)) {
 515                 $model_name = $lower_model.‘_model‘;
 516                 if(!class_exists($model_name,false)){
 517                     require($model_file);
 518                     if(!class_exists($model_name)){
 519                         pigcms_tips($model_name.‘ 类不存在。‘,‘none‘);
 520                     }
 521                 }
 522         $model_obj = new $model_name($model);
 523         return $model_obj;
 524           }else{
 525 
 526              pigcms_tips($model_file.‘ 文件不存在。‘,‘none‘);
 527           }
 528     }
 529 }
 530 
 531 function datetime($unix_time){
 532     return date(‘Y-m-d H:i:s‘,$unix_time);
 533 }
 534 
 535 
 536 function W($model){
 537     $lower_model = strtolower($model);//source/plugins/bonus/model/bonus_model.php‘
 538     $model_file = PIGCMS_PATH.‘source/plugins/bonus/model/‘.$lower_model.‘_model.php‘;
 539     if(file_exists($model_file)){
 540         $model_name = $lower_model.‘_model‘;
 541         if(!class_exists($model_name,false)){
 542             require($model_file);
 543             if(!class_exists($model_name)){
 544                 pigcms_tips($model_name.‘ 类不存在。‘,‘none‘);
 545             }
 546         }
 547         $model_obj = new $model_name($model);
 548         return $model_obj;
 549     }else{
 550         pigcms_tips($model_file.‘ 文件不存在。‘,‘none‘);
 551     }
 552 }
 553 /**
 554  * 浏览器友好的变量输出
 555  * @param mixed $var 变量
 556  * @param boolean $echo 是否输出 默认为True 如果为false 则返回输出字符串
 557  * @param string $label 标签 默认为空
 558  * @param boolean $strict 是否严谨 默认为true
 559  * @return void|string
 560  */
 561 function dump($var, $echo=true, $label=null, $strict=true) {
 562     $label = ($label === null) ? ‘‘ : rtrim($label) . ‘ ‘;
 563     if (!$strict) {
 564         if (ini_get(‘html_errors‘)) {
 565             $output = print_r($var, true);
 566             $output = ‘<pre>‘ . $label . htmlspecialchars($output, ENT_QUOTES) . ‘</pre>‘;
 567         } else {
 568             $output = $label . print_r($var, true);
 569         }
 570     } else {
 571         ob_start();
 572         var_dump($var);
 573         $output = ob_get_clean();
 574         if (!extension_loaded(‘xdebug‘)) {
 575             $output = preg_replace(‘/\]\=\>\n(\s+)/m‘, ‘] => ‘, $output);
 576             $output = ‘<pre>‘ . $label . htmlspecialchars($output, ENT_QUOTES) . ‘</pre>‘;
 577         }
 578     }
 579     if ($echo) {
 580         echo($output);
 581         return null;
 582     }else
 583         return $output;
 584 }
 585 
 586 /**
 587  * 引入模板显示模板
 588  */
 589 /*function display($tpl=‘‘){
 590     global $_G;
 591     $now_group = GROUP_NAME;
 592     $now_module = MODULE_NAME;
 593     $now_action = ACTION_NAME;
 594     $now_theme = $_G[‘config‘][‘theme_‘.$now_group.‘_group‘];
 595 
 596 
 597     if(empty($now_theme)) $now_theme = ‘default‘;
 598     if(empty($tpl)){
 599         $tpl_file = $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.$now_action.‘.php‘;
 600     }else{
 601         $tpl_arr = explode(‘:‘,$tpl);
 602         $tpl_arr_count = count($tpl_arr);
 603         switch($tpl_arr_count){
 604             case 1:
 605                 if($now_group == ‘wap‘ && option(‘config.is_diy_template‘)){
 606 
 607                     if(file_exists(TPL_PATH.$now_group.‘/‘.$now_theme.‘/theme/‘.$tpl_arr[$tpl_arr_count-1].‘.php‘)){
 608                         if(USE_FRAMEWORK){
 609                             $tpl_file = $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.‘/theme/‘.$tpl_arr[$tpl_arr_count-1].‘.php‘;
 610                         }else{
 611                             $tpl_file = $now_group.‘/‘.$now_theme.‘/theme/‘.$tpl_arr[$tpl_arr_count-1].‘.php‘;
 612                         }
 613                     }else{
 614 
 615                         if(USE_FRAMEWORK){
 616                             $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 617                         }else{
 618                             $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 619                         }
 620 
 621                     }
 622 
 623                 }else{
 624 
 625                     if(USE_FRAMEWORK){
 626                         $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 627                     }else{
 628                         $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 629                     }
 630 
 631                 }
 632 
 633                 break;
 634             case 2:
 635                 $tpl_file = $now_group.‘/‘.$now_theme.‘/‘.$tpl_arr[0].‘/‘.$tpl_arr[1].‘.php‘;
 636                 break;
 637             case 3:
 638                 $tpl_file = $tpl_arr[0].‘/‘.$_G[‘config‘][‘theme_‘.$tpl_arr[0].‘_group‘].‘/‘.$tpl_arr[1].‘/‘.$tpl_arr[2].‘.php‘;
 639                 break;
 640             default:
 641                 pigcms_tips(‘参数过多,无法实例化模板!‘);
 642         }
 643         if($tpl_arr_count == 1){
 644             
 645         }else if($tpl_arr_count == 2){
 646             
 647         }else if($tpl_arr_count == 3){
 648             
 649         }
 650     }
 651 
 652     if(file_exists(TPL_PATH.$tpl_file)){
 653         return TPL_PATH.$tpl_file;
 654     }else{
 655         if(DEBUG){
 656             pigcms_tips(‘模板文件 template/‘.$tpl_file.‘ 文件不存在。‘,‘none‘);
 657         }else{
 658             pigcms_tips(‘模板文件 不存在!‘);
 659         }
 660     }
 661 }*/
 662 function plu_url($m,$c)
 663 {
 664         global $_G;
 665     
 666         $return_url = $_G[‘config‘][‘site_url‘].‘/‘;
 667        $return_url.=  "./plugin.php?plugin=site&p=user&m=$m&c=$c";
 668       echo $return_url;
 669 
 670 }
 671 function disp($m,$c)
 672 {
 673     $tpl_file =‘./source/plugins/bonus/view/‘.$m.‘/‘.$c.‘.php‘;
 674     return $tpl_file;
 675 }
 676 
 677 function disps($do,$m,$c)
 678 {
 679     $tpl_file =‘./source/plugins/‘.$do.‘/view/‘.$m.‘/‘.$c.‘.php‘;
 680     return $tpl_file;
 681 }
 682 
 683 function display($tpl=‘‘){
 684     global $_G;
 685     $now_group = GROUP_NAME;
 686     $now_module = MODULE_NAME;
 687     $now_action = ACTION_NAME;
 688     $now_theme = $_G[‘config‘][‘theme_‘.$now_group.‘_group‘];
 689 
 690 
 691     if(empty($now_theme)) $now_theme = ‘default‘;
 692     if(empty($tpl)){
 693         $tpl_file = $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.$now_action.‘.php‘;
 694     }else{
 695         $tpl_arr = explode(‘:‘,$tpl);
 696         $tpl_arr_count = count($tpl_arr);
 697         switch($tpl_arr_count){
 698             case 1:
 699                 if($now_group == ‘wap‘ && option(‘config.is_diy_template‘)){
 700 
 701                     if(file_exists(TPL_PATH.$now_group.‘/‘.$now_theme.‘/theme/‘.$tpl_arr[$tpl_arr_count-1].‘.php‘)){
 702                         if(USE_FRAMEWORK){
 703                             $tpl_file = $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.‘/theme/‘.$tpl_arr[$tpl_arr_count-1].‘.php‘;
 704                         }else{
 705                             $tpl_file = $now_group.‘/‘.$now_theme.‘/theme/‘.$tpl_arr[$tpl_arr_count-1].‘.php‘;
 706                         }
 707                     }else{
 708 
 709                         if(USE_FRAMEWORK){
 710                             $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 711                         }else{
 712                             $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 713                         }
 714 
 715                     }
 716 
 717                 }else{
 718 
 719                     if(USE_FRAMEWORK){
 720                         $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$now_module.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 721                     }else{
 722                         $tpl_file = (strpos($tpl_arr[0],‘/‘)===false) ? $now_group.‘/‘.$now_theme.‘/‘.$tpl_arr[0].‘.php‘ : $tpl_arr[0];
 723                     }
 724 
 725                 }
 726 
 727                 break;
 728             case 2:
 729                 $tpl_file = $now_group.‘/‘.$now_theme.‘/‘.$tpl_arr[0].‘/‘.$tpl_arr[1].‘.php‘;
 730                 break;
 731             case 3:
 732                 $tpl_file = $tpl_arr[0].‘/‘.$_G[‘config‘][‘theme_‘.$tpl_arr[0].‘_group‘].‘/‘.$tpl_arr[1].‘/‘.$tpl_arr[2].‘.php‘;
 733                 break;
 734             default:
 735               $tpl_file =‘./source/plugins/‘.$tpl_arr[2].‘/view/‘.$tpl_arr[4].‘/‘.$tpl_arr[5].‘.php‘;
 736               //echo $tpl_file;die;
 737               //$tpl_file =‘./source/plugins/bonus/view/‘.$tpl_arr[4].‘/‘.$tpl_arr[5].‘.php‘;
 738             
 739         }
 740         if($tpl_arr_count == 1){
 741             
 742         }else if($tpl_arr_count == 2){
 743             
 744         }else if($tpl_arr_count == 3){
 745             
 746         }
 747     }
 748     //var_dump(TPL_PATH.$tpl_file);die;
 749     if(file_exists(TPL_PATH.$tpl_file)){
 750         return TPL_PATH.$tpl_file;
 751     }else{
 752         if(DEBUG){
 753             pigcms_tips(‘模板文件 template/‘.$tpl_file.‘ 文件不存在。‘,‘none‘);
 754         }else{
 755             return $tpl_file;
 756             pigcms_tips(‘模板文件 不存在!‘);
 757         }
 758     }
 759 }
 760 
 761 /**
 762  * 生成URL
 763  */
 764 function url($url=‘‘,$param=array(),$showDomain=false){
 765     global $_G;
 766     if($showDomain){
 767         $return_url = $_G[‘config‘][‘site_url‘].‘/‘;
 768     }else{
 769         $return_url = getWebUrl();
 770     }
 771     $url_arr = explode(‘:‘,$url);
 772     
 773     $url_arr_count = count($url_arr);
 774     switch($url_arr_count){
 775         case 1:
 776             $return_url .= ltrim($_SERVER[‘SCRIPT_NAME‘],‘/‘).‘?c=‘.MODULE_NAME.‘&a=‘.$url_arr[0];
 777             break;
 778         case 2:
 779             $return_url .= ltrim($_SERVER[‘SCRIPT_NAME‘],‘/‘).‘?c=‘.$url_arr[0].‘&a=‘.$url_arr[1];
 780             break;
 781         case 3:
 782             $return_url .= $url_arr[0].‘.php‘.‘?c=‘.$url_arr[1].‘&a=‘.$url_arr[2];
 783             break;
 784         case 4:
 785             pigcms_tips(‘参数过多,只允许接收3个参数!‘);
 786     }
 787     if($param){
 788         $return_url .= ‘&‘.http_build_query($param);
 789     }
 790     return $return_url;
 791 }
 792 function urls($u)
 793 {
 794     //var_dump($u);
 795     
 796     $a ="index.php?c=category&a=index&id=$u";
 797 return $a;
 798 }
 799 //将url转换成静态url  
 800 function url_rewrite($file,$params = array (),$html = "",$rewrite = true) {    
 801      if ($rewrite) {
 802         if(strpos($file,‘:‘)){
 803             $file     = substr($file, 0, strpos($file, ‘:‘));
 804             //echo $file;die;
 805             $url = option(‘config.site_url‘).‘/index.php?c=‘ . $file;
 806         }else{
 807             $url = ($file == ‘index‘) ? ‘‘ : ‘/index.php?c=‘ . $file;  
 808         }
 809          $url .=‘&index&id=‘;
 810         if (!empty ($html)) {  
 811              //$url .= ‘.‘ . $html;  
 812         }
 813 
 814         if (!empty ($params) && is_array($params)) {  
 815             $url .= implode(‘/‘, $params);  
 816         }
 817 
 818         if($file == ‘goods‘ || $file == ‘store‘){
 819             //$url .= ‘.‘ . ‘html‘; 
 820         }
 821 
 822         /*foreach ($params as $key => $value) {  index.php?c=goods&a=index&id=$1
 823             $url .= ‘/‘.$key.‘/‘.$value;
 824         }*/
 825 
 826      } else {
 827         $url     = url($file,$params);
 828     }
 829     //echo $url;die;
 830     return $url;
 831 }
 832 //将url转换成静态url  
 833 function url_rewrites($file,$params = array (),$html = "",$rewrite = true) {    
 834      if ($rewrite) {
 835         if(strpos($file,‘:‘)){
 836             $file     = substr($file, 0, strpos($file, ‘:‘));
 837             $url = option(‘config.site_url‘).‘/‘ . $file;
 838         }else{
 839             $url = ($file == ‘index‘) ? ‘‘ : ‘/‘ . $file;  
 840         }
 841 
 842         if (!empty ($html)) {  
 843              $url .= ‘.‘ . $html;  
 844         }
 845 
 846         if (!empty ($params) && is_array($params)) {  
 847             $url .= ‘/‘ . implode(‘/‘, $params);  
 848         }
 849 
 850         if($file == ‘goods‘ || $file == ‘store‘){
 851             $url .= ‘.‘ . ‘html‘; 
 852         }
 853 
 854         /*foreach ($params as $key => $value) {
 855             $url .= ‘/‘.$key.‘/‘.$value;
 856         }*/
 857 
 858      } else {
 859         $url     = url($file,$params);
 860     }
 861     return $url;
 862 }
 863 
 864 /**
 865  * 生成URL并输出
 866  */
 867 function dourl($url=‘‘,$param=array(),$showDomain=false){
 868     echo url($url,$param,$showDomain);
 869 }
 870 
 871 /**
 872  * 得到字符串的一部分
 873  */
 874 function msubstr($str, $start=0, $length,$suffix=true,$charset="utf-8"){
 875     if(function_exists("mb_substr")){
 876         if ($suffix && strlen($str)>$length)
 877             return mb_substr($str, $start, $length, $charset)."...";
 878         else
 879             return mb_substr($str, $start, $length, $charset);
 880     }
 881     elseif(function_exists(‘iconv_substr‘)) {
 882         if ($suffix && strlen($str)>$length)
 883             return iconv_substr($str,$start,$length,$charset)."...";
 884         else
 885             return iconv_substr($str,$start,$length,$charset);
 886     }
 887     $re[‘utf-8‘]   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
 888     $re[‘gb2312‘] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
 889     $re[‘gbk‘]    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
 890     $re[‘big5‘]   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
 891     preg_match_all($re[$charset], $str, $match);
 892     $slice = join("",array_slice($match[0], $start, $length));
 893     if($suffix) return $slice."…";
 894     return $slice;
 895 }
 896 
 897 /**
 898  * 得到字符串的utf8格式
 899  */
 900 function get_utf8($word){ 
 901     if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true){ 
 902         return $word; 
 903     }else{ 
 904         return iconv(‘gbk‘,‘utf-8‘,$word); 
 905     } 
 906 }
 907 
 908 /**
 909  * JSON返回
 910  *
 911  * param err_code 返回的错误编码
 912  * param err_msg  返回的错误信息
 913  * param err_dom  返回的DOM标识
 914  */
 915 function clear_html($array) 
 916 
 917      {
 918 
 919             if (!is_array($array))
 920 
 921                 return trim(htmlspecialchars($array, ENT_QUOTES));
 922 
 923             foreach ($array as $key => $value) {
 924 
 925                 if (is_array($value)) {
 926 
 927                     $this->clear_html($value);
 928 
 929                 } else {
 930 
 931                     $array[$key] = trim(htmlspecialchars($value, ENT_QUOTES));
 932 
 933                 }
 934 
 935             }
 936 
 937             return $array;
 938 
 939      }
 940 
 941 
 942 
 943 function dexit($data = ‘‘) 
 944 
 945     {
 946 
 947             if (is_array($data)) {
 948 
 949                 echo json_encode($data);
 950 
 951             } else {
 952 
 953                 echo $data;
 954 
 955             }
 956 
 957             exit();
 958 
 959     }
 960 
 961 
 962 function json_return($err_code,$err_msg=‘‘,$err_dom=‘‘){
 963     $json_arr[‘err_code‘] = $err_code;
 964     if($err_msg) $json_arr[‘err_msg‘] = $err_msg;
 965     if($err_dom) $json_arr[‘err_dom‘] = $err_dom;
 966     if(!headers_sent()) header(‘Content-type:application/json‘);
 967     exit(json_encode($json_arr));
 968 }
 969  
 970  
 971 /**
 972  * 检测插件是否存在
 973  *
 974  * @param string $plugin 插件名称
 975  * @param string $attr 参数
 976  */
 977 /*function check_plugin($plugin){
 978     if (is_string($plugin) && file_exists(PIGCMS_PATH.‘source/plugins/‘.$plugin.‘/‘.$plugin.‘.php‘)){
 979         return true;
 980     }else{
 981         return false;
 982     }
 983 }*/
 984 function check_plugin($plugin){
 985     if (is_string($plugin) && file_exists(PIGCMS_PATH.‘source/plugins/‘.$plugin.‘.php‘)){
 986         return true;
 987     }else{
 988         return false;
 989     }
 990 }
 991 
 992 /**
 993  * 得到插件的url
 994  *
 995  * @param string $plugin 插件名称
 996  * @param string $attr 参数 
 997  */
 998 function url_plugin($plugin,$attr=‘‘){
 999     global $_G;
1000     if(!defined(‘IS_MOBILE‘)){
1001         $site_url = $_G[‘config‘][‘site_url‘];
1002     }else{
1003         $site_url = $_G[‘config‘][‘mobile_site_url‘];
1004     }
1005     if(!empty($attr)){
1006         return $site_url.‘/index.php?plugin=‘.$plugin.‘&‘.$attr;
1007     }else{
1008         return $site_url.‘/index.php?plugin=‘.$plugin;
1009     }
1010 }
1011 
1012 /**
1013  * 得到文件的大小
1014  */
1015 function getSize($size){
1016     $kb = 1024;
1017     $mb = 1024*$kb;
1018     $gb = 1024*$mb;
1019     $tb = 1024*$gb;
1020     if($size<$kb){ 
1021         return $size." B";
1022     }else if($size<$mb){ 
1023         return round($size/$kb,2)." KB";
1024     }else if($size<$gb){ 
1025         return round($size/$mb,2)." MB";
1026     }else if($size<$tb){ 
1027         return round($size/$gb,2)." GB";
1028     }else{ 
1029         return round($size/$tb,2)." TB";
1030     }
1031 }
1032 
1033 /**
1034  * 判断是否手机访问
1035  */
1036 function is_mobile(){
1037     if(preg_match(‘/(iphone|ipad|ipod|android)/i‘, strtolower($_SERVER[‘HTTP_USER_AGENT‘]))){
1038         return true;
1039     }else{
1040         return false;
1041     }
1042 }
1043 /**
1044  * 判断是否微信访问
1045  */
1046 function is_weixin(){
1047     if(strpos($_SERVER[‘HTTP_USER_AGENT‘],‘MicroMessenger‘) !== false){
1048         return true;
1049     }else{
1050         return false;
1051     }
1052 }
1053 /**
1054  * 得到附件的网址
1055  * is_remote,是否是远程,否时直接用本地图片
1056  */
1057 function getAttachmentUrl($fileUrl, $is_remote = true){
1058 
1059     if(empty($fileUrl)){
1060         return ‘‘;
1061     }else{
1062         // 如果已经是完整url地址,则不做处理
1063         if (strstr($fileUrl, ‘http://‘) !== false) {
1064             return $fileUrl;
1065         }
1066 
1067         $attachment_upload_type = option(‘config.attachment_upload_type‘);
1068         $url = option(‘config.site_url‘) . ‘/upload/‘;
1069         if ($attachment_upload_type == ‘1‘ && $is_remote) {
1070             $url = ‘http://‘ . option(‘config.attachment_up_domainname‘) . ‘/‘;
1071         }
1072 
1073         return $url . $fileUrl;
1074     }
1075 }
1076 /**
1077  * 得到附件相对应网站目录的文件地址
1078  */
1079 function getAttachmentFilePath($fileUrl){
1080     return PIGCMS_PATH.‘upload/‘.$fileUrl;
1081 }
1082 
1083 /**
1084  * 获取客户端IP地址
1085  * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
1086  * @return mixed
1087  */
1088 function get_client_ip($type = 0) {
1089     $type       =  $type ? 1 : 0;
1090     static $ip  =   NULL;
1091     if ($ip !== NULL) return $ip[$type];
1092     if (isset($_SERVER[‘HTTP_X_FORWARDED_FOR‘])) {
1093         $arr    =   explode(‘,‘, $_SERVER[‘HTTP_X_FORWARDED_FOR‘]);
1094         $pos    =   array_search(‘unknown‘,$arr);
1095         if(false !== $pos) unset($arr[$pos]);
1096         $ip     =   trim($arr[0]);
1097     }elseif (isset($_SERVER[‘HTTP_CLIENT_IP‘])) {
1098         $ip     =   $_SERVER[‘HTTP_CLIENT_IP‘];
1099     }elseif (isset($_SERVER[‘REMOTE_ADDR‘])) {
1100         $ip     =   $_SERVER[‘REMOTE_ADDR‘];
1101     }
1102     // IP地址合法验证
1103     $long = sprintf("%u",ip2long($ip));
1104     $ip   = $long ? array($ip, $long) : array(‘0.0.0.0‘, 0);
1105     return $ip[$type];
1106 }
1107 
1108 
1109 /**
1110  * 等比例绽放图片大小
1111  */
1112  function drawImg($from,$w=100,$h=100,$newfile){
1113 
1114     $info = getimagesize($from);
1115 
1116     switch ($info[2]){
1117         case 1:
1118             $im = imagecreatefromgif($from);
1119             break;
1120 
1121         case 2:
1122             $im = imagecreatefromjpeg($from);
1123             break;
1124 
1125         case 3:
1126             $im = imagecreatefrompng($from);
1127             break;
1128 
1129         default:
1130             exit(‘不支持的图像格式‘);
1131             break;
1132     }
1133 
1134     $temp = pathinfo($from);
1135     $name = $temp["basename"];//文件名
1136     $dir = $temp["dirname"];//文件所在的文件夹
1137     $extension = $temp["extension"];//文件扩展名
1138     $width = $info[0];//获取图片宽度
1139     $height = $info[1];//获取图片高度
1140     $per1 = round($width/$height,2);//计算原图长宽比
1141     $per2 = round($w/$h,2);//计算缩略图长宽比
1142 
1143     //计算缩放比例
1144     if($per1>$per2||$per1==$per2) {
1145         //原图长宽比大于或者等于缩略图长宽比,则按照宽度优先
1146         $per=$w/$width;
1147     }
1148 
1149     if($per1<$per2) {
1150         //原图长宽比小于缩略图长宽比,则按照高度优先
1151         $per=$h/$height;
1152     }
1153     $temp_w = intval($width*$per);//计算原图缩放后的宽度
1154     $temp_h = intval($height*$per);//计算原图缩放后的高度
1155     $dst_im = imagecreatetruecolor($temp_w, $temp_h);
1156 
1157     //调整大小
1158     imagecopyresized($dst_im, $im, 0, 0, 0, 0, $temp_w, $temp_h, $width, $height);
1159     //输出缩小后的图像
1160     //exit($newfile);
1161 
1162     imagejpeg($dst_im,$dir.‘/‘.$newfile);
1163     imagedestroy($dst_im);
1164     imagedestroy($im);
1165 }
1166 
1167 /**
1168  * 获取图片不包含域名,如果未使用远程存储,将upload目录一并去掉
1169  */
1170 function getAttachment($file) {
1171     if (empty($file)) {
1172         return;
1173     }
1174 
1175     $search = trim(option(‘config.site_url‘), ‘/‘) . ‘/upload/‘;
1176     $attachment_upload_type = option(‘config.attachment_upload_type‘);
1177     if ($attachment_upload_type == ‘1‘) {
1178         $search = trim(‘http://‘ . option(‘config.attachment_up_domainname‘), ‘/‘) . ‘/‘;
1179     }
1180 
1181     $file = trim(str_replace($search, ‘‘, $file), ‘/‘);
1182     return $file;
1183 }
1184 
1185 
1186 //im聊天相关
1187 /**
1188  *   加密串
1189  */
1190 function get_encrypt_key($array,$app_key){
1191     $new_arr = array();
1192     ksort($array);
1193     foreach($array as $key=>$value){
1194         $new_arr[] = $key.‘=‘.$value;
1195     }
1196     $new_arr[] = ‘app_key=‘.$app_key;
1197 
1198     $string = implode(‘&‘,$new_arr);
1199     return md5($string);
1200 }
1201 
1202 /**
1203  * CURL POST
1204  *
1205  * param url 抓取的URL
1206  * param data post的数组
1207  */
1208 function curl_post($url,$data){
1209     $ch = curl_init();
1210     $headers[] = "Accept-Charset: utf-8";
1211     curl_setopt($ch, CURLOPT_URL, $url);
1212     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
1213     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
1214     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
1215     curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
1216     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
1217     curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)‘);
1218     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1219     curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
1220     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
1221     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
1222     $result = curl_exec($ch);
1223 
1224     //关闭curl
1225     curl_close($ch);
1226     
1227     return $result;
1228 }
1229 /**
1230  * 微信API CURL POST
1231  *
1232  * param url 抓取的URL
1233  * param data post的数组
1234  */
1235 function api_curl_post($url,$data){
1236     $result = curl_post($url,$data);
1237 
1238     $result_arr = json_decode($result,true);
1239     return $result_arr;
1240 }
1241 
1242 /**
1243  * JSON返回
1244  *
1245  * param err_code 返回的错误编码
1246  * param err_msg  返回的错误信息
1247  * param err_dom  返回的DOM标识
1248  */
1249 function error_json_return($err_code,$err_msg){
1250     $json_arr[‘err_code‘] = $err_code;
1251     $json_arr[‘err_msg‘] = $err_msg;
1252     exit(json_encode($json_arr));
1253 }
1254 function ok_json_return($json_arr){
1255     $json_arr[‘err_code‘] = 0;
1256     exit(json_encode($json_arr));
1257 }
1258 function ok_jsonp_return($json_arr){
1259     $json_arr[‘err_code‘] = 0;
1260     exit($_GET[‘callback‘].‘(‘.json_encode($json_arr).‘)‘);
1261 }
1262 //获取im聊天url
1263 function getImUrl($userId,$storeId){
1264     $is_service     = D(‘Service‘)->where("status = 1 AND openid != ‘‘ AND store_id=$storeId")->find();
1265     
1266     if(!empty($is_service) && $_SESSION[‘wap_user‘][‘app_id‘] == 0){
1267         $key = get_encrypt_key(array(‘app_id‘=>option(‘config.im_appid‘),‘openid‘=>$userId),option(‘config.im_appkey‘));
1268         $url = IM_SERVER_PATH.‘?app_id=‘.option(‘config.im_appid‘).‘&openid=‘.$userId.‘&key=‘.$key.‘#serviceList_‘.$storeId;
1269     }else{
1270         $store = D(‘Store‘)->where("status = 1 AND store_id = ‘" . $storeId . "‘")->find();
1271         $user_tmp = $_SESSION[‘wap_user‘];
1272         
1273         /*if (empty($_SESSION[‘wap_user‘])) {
1274             $user_tmp = D(‘User‘)->where("uid = ‘" . $store[‘uid‘] . "‘")->find();
1275         }*/
1276         
1277         if ($user_tmp[‘app_id‘] == 1 && !empty($store[‘open_service‘]) && !empty($store[‘source_site_url‘]) && !empty($store[‘token‘])) {
1278             $url = $store[‘source_site_url‘] . ‘/index.php?g=Wap&m=Service&a=index&token=‘ . $store[‘token‘] . ‘&wecha_id=‘;
1279         } else if ($user_tmp[‘app_id‘] == 2 && !empty($store[‘open_service‘])) {
1280             $url = $store[‘source_site_url‘] . ‘/wap.php?c=Weidian&a=getImUrl&token=‘.$store[‘token‘].‘&wecha_id=‘.$_SESSION[‘wap_user‘][‘third_id‘];
1281         } else {
1282             $url     = ‘‘;
1283         }
1284     }
1285     
1286     return $url;
1287 }
1288 
1289 /**
1290  * 根据时间,返回状态
1291  * 当前时间在两个时间内:正在进行,当前时间大于开始时间:未开始,当前时间大于结束时间:已结束
1292  */
1293 function getTimeType($start_time, $end_time) {
1294     if (empty($start_time) && empty($end_time)) {
1295         return ‘‘;
1296     }
1297 
1298     // 时间修正
1299     if ($start_time > $end_time) {
1300         $tmp = $end_time;
1301         $end_time = $start_time;
1302         $start_time = $tmp;
1303     }
1304 
1305     $time = time();
1306     if ($time >= $start_time && $time <= $end_time) {
1307         return ‘正在进行‘;
1308     } else if ($time < $start_time) {
1309         return ‘未开始‘;
1310     } else if ($time > $end_time) {
1311         return ‘已结束‘;
1312     }
1313 
1314     return ‘‘;
1315 }
1316 
1317 /**
1318  * 根据满减/送信息,返回格式化字条串
1319  */
1320 function getRewardStr($reward) {
1321     global $config;
1322 
1323     $str = ‘满‘ . $reward[‘money‘];
1324 
1325     if ($reward[‘cash‘]) {
1326         $str .= ‘,减‘ . $reward[‘cash‘] . ‘元‘;
1327     }
1328 
1329     if ($reward[‘postage‘]) {
1330         $str .= ‘,免邮费‘;
1331     }
1332 
1333     if ($reward[‘score‘]) {
1334         $str .= ‘,送‘ . $reward[‘score‘] . ‘积分‘;
1335     }
1336 
1337     if ($reward[‘coupon‘]) {
1338         $str .= ‘,送优惠券‘;
1339 
1340         $url = ‘‘;
1341         if (GROUP_NAME != ‘wap‘) {
1342             $url = url(‘coupon:index‘, array(‘id‘ => $reward[‘coupon‘][‘id‘]));
1343         } else {
1344             $url = $config[‘wap_site_url‘] . ‘/coupon_detail.php?id=‘ . $reward[‘coupon‘][‘id‘];
1345         }
1346         $str .= ‘<a href="‘ . $url . ‘" target="_blank">‘ . $reward[‘coupon‘][‘name‘] . ‘</a>‘;
1347     }
1348 
1349     if ($reward[‘present‘]) {
1350         $str .= ‘,赠送产品:‘;
1351         foreach ($reward[‘present‘] as $product) {
1352             $url = ‘‘;
1353             if (GROUP_NAME != ‘wap‘) {
1354                 $url = url_rewrite(‘goods:index‘, array(‘id‘ => $product[‘product_id‘]));
1355             } else {
1356                 $url = $config[‘wap_site_url‘] . ‘/good.php?id=‘ .  $product[‘product_id‘];
1357             }
1358             $str .= ‘<a href="‘ . $url . ‘" target="_blank">‘ . $product[‘name‘] . ‘</a> ‘;
1359         }
1360     }
1361 
1362     return $str;
1363 }
1364 
1365 
1366 
1367 //对象转换为数组
1368 function object_array($array) {
1369     if(is_object($array)) {
1370         $array = (array)$array;
1371     } if(is_array($array)) {
1372         foreach($array as $key=>$value) {
1373             $array[$key] = object_array($value);
1374         }
1375     }
1376     return $array;
1377 }
1378 
1379 
1380 //获取用户当前登录位置
1381 function show_distance(){
1382 
1383     if($_COOKIE[‘Web_user‘]) {
1384         $array = object_array(json_decode($_COOKIE[‘Web_user‘]));
1385         $array[‘status‘] = true;
1386     } else {
1387         $array = array(‘status‘=>false);
1388     }
1389     return $array;
1390 }
1391 
1392 // 隐藏评论人信息
1393 function anonymous($str, $len1 = 2, $len2 = 1) {
1394     if (mb_strlen($str, ‘utf-8‘) < 4) {
1395         $return_str = mb_substr($str, 0, 1, ‘utf-8‘);
1396         $return_str .= ‘**‘;
1397     } else {
1398         $return_str = mb_substr($str, 0, $len1, ‘utf-8‘);
1399         $return_str .= ‘**‘;
1400         $return_str .= mb_substr($str, -1 * $len2, $len2, ‘utf-8‘);
1401     }
1402     return $return_str;
1403 }
1404 
1405 
1406 /**
1407  * @desc 获取querystring
1408  * @param $url
1409  * @return array|string
1410  */
1411 function convertUrlQuery($url) {
1412     $arr = parse_url($url);
1413     $query = $arr[‘query‘];
1414     if (!empty($query)) {
1415         $queryParts = explode(‘&‘, $query);
1416 
1417         $params = array();
1418         foreach ($queryParts as $param) {
1419             $item = explode(‘=‘, $param);
1420             $params[$item[0]] = $item[1];
1421         }
1422     } else {
1423         $params = ‘‘;
1424     }
1425     return $params;
1426 }
1427 
1428 
1429 
1430 
1431 /**
1432  *计算某个经纬度的周围某段距离的正方形的四个点
1433  *
1434  *@param lng float 经度
1435  *@param lat float 纬度
1436  *@param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米
1437  *@return array 正方形的四个点的经纬度坐标
1438 */
1439 function returnSquarePoint($lng, $lat,$distance = 0.5){
1440     define(EARTH_RADIUS, 6371);//地球半径,平均半径为6371km
1441     $dlng =  2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat)));
1442     $dlng = rad2deg($dlng);
1443 
1444     $dlat = $distance/EARTH_RADIUS;
1445     $dlat = rad2deg($dlat);
1446 
1447     return array(
1448             ‘left-top‘=>array(‘lat‘=>$lat + $dlat,‘lng‘=>$lng-$dlng),
1449             ‘right-top‘=>array(‘lat‘=>$lat + $dlat, ‘lng‘=>$lng + $dlng),
1450             ‘left-bottom‘=>array(‘lat‘=>$lat - $dlat, ‘lng‘=>$lng - $dlng),
1451             ‘right-bottom‘=>array(‘lat‘=>$lat - $dlat, ‘lng‘=>$lng + $dlng)
1452     );
1453 }
1454 
1455     function arr2_arr1($arrdata,$v)
1456     {
1457         $arrs = array();
1458         foreach ($arrdata as $key => $value) {
1459             $arrs[] = $value[$v];
1460         }
1461         return $arrs;
1462     }
1463 
1464     function dangqiangIp()
1465     {
1466 
1467         $ip = "Unknown";
1468 
1469         if (isset($_SERVER["HTTP_X_REAL_IP"]) && !empty($_SERVER["HTTP_X_REAL_IP"])) {
1470             $ip = $_SERVER["HTTP_X_REAL_IP"];
1471         }
1472         elseif (isset($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"]) && !empty($HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"])) {
1473             $ip = $HTTP_SERVER_VARS["HTTP_X_FORWARDED_FOR"];
1474         }
1475         elseif (isset($HTTP_SERVER_VARS["HTTP_CLIENT_IP"]) && !empty($HTTP_SERVER_VARS["HTTP_CLIENT_IP"])) {
1476             $ip = $HTTP_SERVER_VARS["HTTP_CLIENT_IP"];
1477         }
1478         elseif (isset($HTTP_SERVER_VARS["REMOTE_ADDR"]) && !empty($HTTP_SERVER_VARS["REMOTE_ADDR"])) {
1479             $ip = $HTTP_SERVER_VARS["REMOTE_ADDR"];
1480         }
1481         elseif (getenv("HTTP_X_FORWARDED_FOR")) {
1482             $ip = getenv("HTTP_X_FORWARDED_FOR");
1483         }
1484         elseif (getenv("HTTP_CLIENT_IP")) {
1485             $ip = getenv("HTTP_CLIENT_IP");
1486         }
1487         elseif (getenv("REMOTE_ADDR")) {
1488             $ip = getenv("REMOTE_ADDR");
1489         }
1490         return $ip;
1491     }
1492 ?>
1493 
1494 <!DOCTYPE html>
1495 <html lang="en">
1496 <head>
1497     <meta charset="UTF-8">
1498     <title>Document</title>
1499 </head>
1500 <body>
1501     
1502 </body>
1503 </html>
1504 <script type="text/javascript">
1505     
1506     $.ajax({
1507                         type:‘get‘,
1508                         url:‘/merchants.php?m=User&c=index&a=delmen&id=‘+ids,
1509                         dataType:"JSON",
1510                         success:function(ret){
1511                             //alert(ret.error);
1512                                 if(ret.error== 2){
1513                                          swal({
1514                                               title: "公众号菜单!",
1515                                               text: ret.msg,
1516                                               type: "success"
1517                                              }, function () {
1518                                             window.location.reload();
1519                                             });
1520                                       
1521                                 }else{
1522                                     swal({
1523                                               title: "公众号菜单!",
1524                                               text: ret.msg,
1525                                               type: "error"
1526                                              }, function () {
1527                                             window.location.reload();
1528                                             });
1529                                 }
1530                         }
1531                     });
1532 //========================
1533     $.get(‘?m=User&c=cashier&a=restore‘,{orderid:c.attr(‘data-id‘)},function(re){
1534                             if(re.status == 0){
1535                                 swal("错误", "还原失败 :)", "error");
1536                             }else{
1537                                 swal("成功", "还原成功 :)", "success");
1538                                 c.parents(‘tr‘).remove();
1539                                 b(‘.footable‘).footable();
1540                             }
1541                         },‘json‘);
1542                     });
1543 
1544  //=================================
1545 </script>
1546 
1547 <script>
1548     $(function(){
1549       $(‘#submit‘).click(function() {
1550           var postData={
1551             geetest_challenge: $(‘.geetest_challenge‘).val(),
1552             geetest_validate: $(‘.geetest_validate‘).val(),
1553             geetest_seccode: $(‘.geetest_seccode‘).val()
1554         }            
1555         postData.username = $("input[name=‘username‘]").val();
1556         postData.password = $("input[name=‘password‘]").val();
1557         postData.type = $("input[name=‘type‘]:checked").val();
1558 
1559       console.log(postData);//success
1560       $.post(‘merchants.php?m=Index&c=index&a=signin_test‘, postData, function(ret){
1561           console.log(ret.msg);
1562             if (ret.error == 0){
1563                window.location.href=ret.msg;
1564                 //window.location.href="/merchants.php?m=User&c=souye&a=souye"; 
1565                //swal("成功", ret.msg, "success");
1566              }else if(ret.error == 1){               
1567                swal("失败", ret.msg, "error");               
1568            }else{
1569                window.location.href=ret.msg;
1570            }
1571         },‘json‘);
1572       
1573       });
1574     });
1575   </script>
View Code

 

以上是关于php常用的函数的主要内容,如果未能解决你的问题,请参考以下文章

C#常用代码片段备忘

56个PHP开发常用代码

php 一个自定义的try..catch包装器代码片段,用于执行模型函数,使其成为一个单行函数调用

超级有用的9个PHP代码片段

常用Javascript代码片段集锦

nodejs常用代码片段