PageRenderTime 35ms CodeModel.GetById 1ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/function/common.function.php

https://gitlab.com/imxieke/XCloud
PHP | 755 lines | 635 code | 18 blank | 102 comment | 48 complexity | 517118481a0a9b2d97f1dcd38218198a MD5 | raw file
  1. <?php
  2. /*
  3. * @link http://www.kalcaddle.com/
  4. * @author warlee | e-mail:kalcaddle@qq.com
  5. * @copyright warlee 2014.(Shanghai)Co.,Ltd
  6. * @license http://kalcaddle.com/tools/licenses/license.txt
  7. */
  8. /**
  9. * 加载类,从class目录;controller;model目录中寻找class
  10. */
  11. function _autoload($className){
  12. if (file_exists(CLASS_DIR . strtolower($className) . '.class.php')) {
  13. require_once(CLASS_DIR . strtolower($className) . '.class.php');
  14. } else if (file_exists(CONTROLLER_DIR . strtolower($className) . '.class.php')) {
  15. require_once(CONTROLLER_DIR . strtolower($className) . '.class.php');
  16. } else if (file_exists(MODEl_DIR . strtolower($className) . '.class.php')) {
  17. require_once(MODEl_DIR . strtolower($className) . '.class.php');
  18. } else {
  19. // error code;
  20. }
  21. }
  22. /**
  23. * 生产model对象
  24. */
  25. function init_model($model_name){
  26. if (!class_exists($model_name.'Model')) {
  27. $model_file = MODEL_DIR.$model_name.'Model.class.php';
  28. require_once ($model_file);
  29. if(!is_file($model_file)){
  30. return false;
  31. }
  32. }
  33. $reflectionObj = new ReflectionClass($model_name.'Model');
  34. $args = func_get_args();
  35. array_shift($args);
  36. return $reflectionObj -> newInstanceArgs($args);
  37. }
  38. /**
  39. * 生产controller对象
  40. */
  41. function init_controller($controller_name){
  42. if (!class_exists($controller_name)) {
  43. $model_file = CONTROLLER_DIR.$controller_name.'.class.php';
  44. if(!is_file($model_file)){
  45. return false;
  46. }
  47. require_once ($model_file);
  48. }
  49. $reflectionObj = new ReflectionClass($controller_name);
  50. $args = func_get_args();
  51. array_shift($args);
  52. return $reflectionObj -> newInstanceArgs($args);
  53. }
  54. /**
  55. * 加载类
  56. */
  57. function load_class($class){
  58. $filename = CLASS_DIR.$class.'.class.php';
  59. if (file_exists($filename)) {
  60. require($filename);
  61. }else{
  62. pr($filename.' is not exist',1);
  63. }
  64. }
  65. /**
  66. * 加载函数库
  67. */
  68. function load_function($function){
  69. $filename = FUNCTION_DIR.$function.'.function.php';
  70. if (file_exists($filename)) {
  71. require($filename);
  72. }else{
  73. pr($filename.' is not exist',1);
  74. }
  75. }
  76. /**
  77. * 文本字符串转换
  78. */
  79. function mystr($str){
  80. $from = array("\r\n", " ");
  81. $to = array("<br/>", "&nbsp");
  82. return str_replace($from, $to, $str);
  83. }
  84. // 清除多余空格和回车字符
  85. function strip($str){
  86. return preg_replace('!\s+!', '', $str);
  87. }
  88. /**
  89. * 获取精确时间
  90. */
  91. function mtime(){
  92. $t= explode(' ',microtime());
  93. $time = $t[0]+$t[1];
  94. return $time;
  95. }
  96. /**
  97. * 过滤HTML
  98. */
  99. function clear_html($HTML, $br = true){
  100. $HTML = htmlspecialchars(trim($HTML));
  101. $HTML = str_replace("\t", ' ', $HTML);
  102. if ($br) {
  103. return nl2br($HTML);
  104. } else {
  105. return str_replace("\n", '', $HTML);
  106. }
  107. }
  108. /**
  109. * 将obj深度转化成array
  110. *
  111. * @param $obj 要转换的数据 可能是数组 也可能是个对象 还可能是一般数据类型
  112. * @return array || 一般数据类型
  113. */
  114. function obj2array($obj){
  115. if (is_array($obj)) {
  116. foreach($obj as &$value) {
  117. $value = obj2array($value);
  118. }
  119. return $obj;
  120. } elseif (is_object($obj)) {
  121. $obj = get_object_vars($obj);
  122. return obj2array($obj);
  123. } else {
  124. return $obj;
  125. }
  126. }
  127. /**
  128. * 计算时间差
  129. *
  130. * @param char $pretime
  131. * @return char
  132. */
  133. function spend_time(&$pretime){
  134. $now = microtime(1);
  135. $spend = round($now - $pretime, 5);
  136. $pretime = $now;
  137. return $spend;
  138. }
  139. function check_code($code){
  140. header("Content-type: image/png");
  141. $fontsize = 18;$len = strlen($code);
  142. $width = 70;$height=27;
  143. $im = @imagecreatetruecolor($width, $height) or die("create image error!");
  144. $background_color = imagecolorallocate($im, 255, 255, 255);
  145. imagefill($im, 0, 0, $background_color);
  146. for ($i = 0; $i < 2000; $i++) {//获取随机淡色
  147. $line_color = imagecolorallocate($im, mt_rand(180,255),mt_rand(160, 255),mt_rand(100, 255));
  148. imageline($im,mt_rand(0,$width),mt_rand(0,$height), //画直线
  149. mt_rand(0,$width), mt_rand(0,$height),$line_color);
  150. imagearc($im,mt_rand(0,$width),mt_rand(0,$height), //画弧线
  151. mt_rand(0,$width), mt_rand(0,$height), $height, $width,$line_color);
  152. }
  153. $border_color = imagecolorallocate($im, 160, 160, 160);
  154. imagerectangle($im, 0, 0, $width-1, $height-1, $border_color);//画矩形,边框颜色200,200,200
  155. for ($i = 0; $i < $len; $i++) {//写入随机字串
  156. $current = $str[mt_rand(0, strlen($str)-1)];
  157. $text_color = imagecolorallocate($im,mt_rand(30, 140),mt_rand(30,140),mt_rand(30,140));
  158. imagechar($im,10,$i*$fontsize+6,rand(1,$height/3),$code[$i],$text_color);
  159. }
  160. imagejpeg($im);//显示图
  161. imagedestroy($im);//销毁图片
  162. }
  163. /**
  164. * 返回当前浮点式的时间,单位秒;主要用在调试程序程序时间时用
  165. *
  166. * @return float
  167. */
  168. function microtime_float(){
  169. list($usec, $sec) = explode(' ', microtime());
  170. return ((float)$usec + (float)$sec);
  171. }
  172. /**
  173. * 计算N次方根
  174. * @param $num
  175. * @param $root
  176. */
  177. function croot($num, $root = 3){
  178. $root = intval($root);
  179. if (!$root) {
  180. return $num;
  181. }
  182. return exp(log($num) / $root);
  183. }
  184. function add_magic_quotes($array){
  185. foreach ((array) $array as $k => $v) {
  186. if (is_array($v)) {
  187. $array[$k] = add_magic_quotes($v);
  188. } else {
  189. $array[$k] = addslashes($v);
  190. }
  191. }
  192. return $array;
  193. }
  194. // 字符串加转义
  195. function add_slashes($string){
  196. if (!$GLOBALS['magic_quotes_gpc']) {
  197. if (is_array($string)) {
  198. foreach($string as $key => $val) {
  199. $string[$key] = add_slashes($val);
  200. }
  201. } else {
  202. $string = addslashes($string);
  203. }
  204. }
  205. return $string;
  206. }
  207. /**
  208. * hex to binary
  209. */
  210. if (!function_exists('hex2bin')) {
  211. function hex2bin($hexdata) {
  212. return pack('H*', $hexdata);
  213. }
  214. }
  215. /**
  216. * 二维数组按照指定的键值进行排序,
  217. *
  218. * @param $keys 根据键值
  219. * @param $type 升序降序
  220. * @return array $array = array(
  221. * array('name'=>'手机','brand'=>'诺基亚','price'=>1050),
  222. * array('name'=>'手表','brand'=>'卡西欧','price'=>960)
  223. * );$out = array_sort($array,'price');
  224. */
  225. function array_sort($arr, $keys, $type = 'asc'){
  226. $keysvalue = $new_array = array();
  227. foreach ($arr as $k => $v) {
  228. $keysvalue[$k] = $v[$keys];
  229. }
  230. if ($type == 'asc') {
  231. asort($keysvalue);
  232. } else {
  233. arsort($keysvalue);
  234. }
  235. reset($keysvalue);
  236. foreach ($keysvalue as $k => $v) {
  237. $new_array[$k] = $arr[$k];
  238. }
  239. return $new_array;
  240. }
  241. /**
  242. * 遍历数组,对每个元素调用 $callback,假如返回值不为假值,则直接返回该返回值;
  243. * 假如每次 $callback 都返回假值,最终返回 false
  244. *
  245. * @param $array
  246. * @param $callback
  247. * @return mixed
  248. */
  249. function array_try($array, $callback){
  250. if (!$array || !$callback) {
  251. return false;
  252. }
  253. $args = func_get_args();
  254. array_shift($args);
  255. array_shift($args);
  256. if (!$args) {
  257. $args = array();
  258. }
  259. foreach($array as $v) {
  260. $params = $args;
  261. array_unshift($params, $v);
  262. $x = call_user_func_array($callback, $params);
  263. if ($x) {
  264. return $x;
  265. }
  266. }
  267. return false;
  268. }
  269. // 求多个数组的并集
  270. function array_union(){
  271. $argsCount = func_num_args();
  272. if ($argsCount < 2) {
  273. return false;
  274. } else if (2 === $argsCount) {
  275. list($arr1, $arr2) = func_get_args();
  276. while ((list($k, $v) = each($arr2))) {
  277. if (!in_array($v, $arr1)) $arr1[] = $v;
  278. }
  279. return $arr1;
  280. } else { // 三个以上的数组合并
  281. $arg_list = func_get_args();
  282. $all = call_user_func_array('array_union', $arg_list);
  283. return array_union($arg_list[0], $all);
  284. }
  285. }
  286. // 取出数组中第n项
  287. function array_get($arr,$index){
  288. foreach($arr as $k=>$v){
  289. $index--;
  290. if($index<0) return array($k,$v);
  291. }
  292. }
  293. function show_tips($message){
  294. echo<<<END
  295. <html>
  296. <style>
  297. #msgbox{border: 1px solid #ddd;border: 1px solid #eee;padding: 30px;border-radius: 5px;background: #f6f6f6;
  298. font-family: 'Helvetica Neue', "Microsoft Yahei", "微软雅黑", "STXihei", "WenQuanYi Micro Hei", sans-serif;
  299. color:888;font-size:13px;margin:0 auto;margin-top:10%;width: 400px;font-size: 16;color:#666;}
  300. #msgbox #title{padding-left:20px;font-weight:800;font-size:25px;}
  301. #msgbox #message{padding:20px;}
  302. </style>
  303. <body>
  304. <div id="msgbox">
  305. <div id="title">tips</div>
  306. <div id="message">$message</div>
  307. </body>
  308. </html>
  309. END;
  310. exit;
  311. }
  312. /**
  313. * 打包返回AJAX请求的数据
  314. * @params {int} 返回状态码, 通常0表示正常
  315. * @params {array} 返回的数据集合
  316. */
  317. function show_json($data,$code = true,$info=''){
  318. $use_time = mtime() - $GLOBALS['config']['app_startTime'];
  319. $result = array('code' => $code,'use_time'=>$use_time,'data' => $data);
  320. if ($info != '') {
  321. $result['info'] = $info;
  322. }
  323. header("X-Powered-By: kodExplorer.");
  324. header('Content-Type: application/json; charset=utf-8');
  325. echo json_encode($result);
  326. exit;
  327. }
  328. /**
  329. * 简单模版转换,用于根据配置获取列表:
  330. * 参数:cute1:第一次切割的字符串,cute2第二次切割的字符串,
  331. * arraylist为待处理的字符串,$this 为标记当前项,$this_str为当项标记的替换。
  332. * $tpl为处理后填充到静态模版({0}代表切割后左值,{1}代表切割后右值,{this}代表当前项填充值)
  333. * 例子:
  334. * $arr="default=淡蓝(默认)=5|mac=mac海洋=6|mac1=mac1海洋=7";
  335. * $tpl="<li class='list {this}' theme='{0}'>{1}_{2}</li>\n";
  336. * echo getTplList('|','=',$arr,$tpl,'mac'),'<br/>';
  337. */
  338. function getTplList($cute1, $cute2, $arraylist, $tpl,$this,$this_str=''){
  339. $list = explode($cute1, $arraylist);
  340. if ($this_str == '') $this_str ="this";
  341. $html = '';
  342. foreach ($list as $value) {
  343. $info = explode($cute2, $value);
  344. $arr_replace = array();
  345. foreach ($info as $key => $value) {
  346. $arr_replace[$key]='{'.$key .'}';
  347. }
  348. if ($info[0] == $this) {
  349. $temp = str_replace($arr_replace, $info, $tpl);
  350. $temp = str_replace('{this}', $this_str, $temp);
  351. } else {
  352. $temp = str_replace($arr_replace, $info, $tpl);
  353. $temp = str_replace('{this}', '', $temp);
  354. }
  355. $html .= $temp;
  356. }
  357. return $html;
  358. }
  359. //获取当前url地址
  360. function get_url() {
  361. $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT']
  362. == '443' ? 'https://' : 'http://';
  363. $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
  364. $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
  365. $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] :
  366. $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
  367. return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
  368. }
  369. /**
  370. * 去掉HTML代码中的HTML标签,返回纯文本
  371. * @param string $document 待处理的字符串
  372. * @return string
  373. */
  374. function html2txt($document){
  375. $search = array ("'<script[^>]*?>.*?</script>'si", // 去掉 javascript
  376. "'<[\/\!]*?[^<>]*?>'si", // 去掉 HTML 标记
  377. "'([\r\n])[\s]+'", // 去掉空白字符
  378. "'&(quot|#34);'i", // 替换 HTML 实体
  379. "'&(amp|#38);'i",
  380. "'&(lt|#60);'i",
  381. "'&(gt|#62);'i",
  382. "'&(nbsp|#160);'i",
  383. "'&(iexcl|#161);'i",
  384. "'&(cent|#162);'i",
  385. "'&(pound|#163);'i",
  386. "'&(copy|#169);'i",
  387. "'&#(\d+);'e"); // 作为 PHP 代码运行
  388. $replace = array ("",
  389. "",
  390. "",
  391. "\"",
  392. "&",
  393. "<",
  394. ">",
  395. " ",
  396. chr(161),
  397. chr(162),
  398. chr(163),
  399. chr(169),
  400. "chr(\\1)");
  401. $text = preg_replace ($search, $replace, $document);
  402. return $text;
  403. }
  404. // 获取内容第一条
  405. function match($content, $preg){
  406. $preg = "/" . $preg . "/isU";
  407. preg_match($preg, $content, $result);
  408. return $result[1];
  409. }
  410. // 获取内容,获取一个页面若干信息.结果在 1,2,3……中
  411. function match_all($content, $preg){
  412. $preg = "/" . $preg . "/isU";
  413. preg_match_all($preg, $content, $result);
  414. return $result;
  415. }
  416. /**
  417. * 获取指定长度的 utf8 字符串
  418. *
  419. * @param string $string
  420. * @param int $length
  421. * @param string $dot
  422. * @return string
  423. */
  424. function get_utf8_str($string, $length, $dot = '...'){
  425. if (strlen($string) <= $length) return $string;
  426. $strcut = '';
  427. $n = $tn = $noc = 0;
  428. while ($n < strlen($string)) {
  429. $t = ord($string[$n]);
  430. if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  431. $tn = 1;
  432. $n++;
  433. $noc++;
  434. } elseif (194 <= $t && $t <= 223) {
  435. $tn = 2;
  436. $n += 2;
  437. $noc += 2;
  438. } elseif (224 <= $t && $t <= 239) {
  439. $tn = 3;
  440. $n += 3;
  441. $noc += 2;
  442. } elseif (240 <= $t && $t <= 247) {
  443. $tn = 4;
  444. $n += 4;
  445. $noc += 2;
  446. } elseif (248 <= $t && $t <= 251) {
  447. $tn = 5;
  448. $n += 5;
  449. $noc += 2;
  450. } elseif ($t == 252 || $t == 253) {
  451. $tn = 6;
  452. $n += 6;
  453. $noc += 2;
  454. } else {
  455. $n++;
  456. }
  457. if ($noc >= $length) break;
  458. }
  459. if ($noc > $length) {
  460. $n -= $tn;
  461. }
  462. if ($n < strlen($string)) {
  463. $strcut = substr($string, 0, $n);
  464. return $strcut . $dot;
  465. } else {
  466. return $string ;
  467. }
  468. }
  469. /**
  470. * 字符串截取,支持中文和其他编码
  471. *
  472. * @param string $str 需要转换的字符串
  473. * @param string $start 开始位置
  474. * @param string $length 截取长度
  475. * @param string $charset 编码格式
  476. * @param string $suffix 截断显示字符
  477. * @return string
  478. */
  479. function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true){
  480. if (function_exists("mb_substr")) {
  481. $i_str_len = mb_strlen($str);
  482. $s_sub_str = mb_substr($str, $start, $length, $charset);
  483. if ($length >= $i_str_len) {
  484. return $s_sub_str;
  485. }
  486. return $s_sub_str . '...';
  487. } elseif (function_exists('iconv_substr')) {
  488. return iconv_substr($str, $start, $length, $charset);
  489. }
  490. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  491. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  492. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  493. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  494. preg_match_all($re[$charset], $str, $match);
  495. $slice = join("", array_slice($match[0], $start, $length));
  496. if ($suffix) return $slice . "…";
  497. return $slice;
  498. }
  499. function web2wap(&$content){
  500. $search = array ("/<img[^>]+src=\"([^\">]+)\"[^>]+>/siU",
  501. "/<a[^>]+href=\"([^\">]+)\"[^>]*>(.*)<\/a>/siU",
  502. "'<br[^>]*>'si",
  503. "'<p>'si",
  504. "'</p>'si",
  505. "'<script[^>]*?>.*?</script>'si", // 去掉 javascript
  506. "'<[\/\!]*?[^<>]*?>'si", // 去掉 HTML 标记
  507. "'([\r\n])[\s]+'", // 去掉空白字符
  508. ); // 作为 PHP 代码运行
  509. $replace = array ("#img#\\1#/img#",
  510. "#link#\\1#\\2#/link#",
  511. "[br]",
  512. "",
  513. "[br]",
  514. "",
  515. "",
  516. "",
  517. );
  518. $text = preg_replace ($search, $replace, $content);
  519. $text = str_replace("[br]", "<br/>", $text);
  520. $img_start = "<img src=\"" . $publish_url . "automini.php?src=";
  521. $img_end = "&amp;pixel=100*80&amp;cache=1&amp;cacheTime=1000&amp;miniType=png\" />";
  522. $text = preg_replace ("/#img#(.*)#\/img#/isUe", "'$img_start'.urlencode('\\1').'$img_end'", $text);
  523. $text = preg_replace ("/#link#(.*)#(.*)#\/link#/isU", "<a href=\"\\1\">\\2</a>", $text);
  524. while (preg_match("/<br\/><br\/>/siU", $text)) {
  525. $text = str_replace('<br/><br/>', '<br/>', $text);
  526. }
  527. return $text;
  528. }
  529. /**
  530. * 获取变量的名字
  531. * eg hello="123" 获取ss字符串
  532. */
  533. function get_var_name(&$aVar){
  534. foreach($GLOBALS as $key => $var) {
  535. if ($aVar == $GLOBALS[$key] && $key != "argc") {
  536. return $key;
  537. }
  538. }
  539. }
  540. // -----------------变量调试-------------------
  541. /**
  542. * 格式化输出变量,或者对象
  543. *
  544. * @param mixed $var
  545. * @param boolean $exit
  546. */
  547. function pr($var, $exit = false){
  548. ob_start();
  549. $style = '<style>
  550. pre#debug{margin:10px;font-size:14px;color:#222;font-family:Consolas ;line-height:1.2em;background:#f6f6f6;border-left:5px solid #444;padding:5px;width:95%;word-break:break-all;}
  551. pre#debug b{font-weight:400;}
  552. #debug #debug_str{color:#E75B22;}
  553. #debug #debug_keywords{font-weight:800;color:00f;}
  554. #debug #debug_tag1{color:#22f;}
  555. #debug #debug_tag2{color:#f33;font-weight:800;}
  556. #debug #debug_var{color:#33f;}
  557. #debug #debug_var_str{color:#f00;}
  558. #debug #debug_set{color:#0C9CAE;}</style>';
  559. if (is_array($var)) {
  560. print_r($var);
  561. } else if (is_object($var)) {
  562. echo get_class($var) . " Object";
  563. } else if (is_resource($var)) {
  564. echo (string)$var;
  565. } else {
  566. echo var_dump($var);
  567. }
  568. $out = ob_get_clean(); //缓冲输出给$out 变量
  569. $out = preg_replace('/"(.*)"/', '<b id="debug_var_str">"' . '\\1' . '"</b>', $out); //高亮字符串变量
  570. $out = preg_replace('/=\>(.*)/', '=>' . '<b id="debug_str">' . '\\1' . '</b>', $out); //高亮=>后面的值
  571. $out = preg_replace('/\[(.*)\]/', '<b id="debug_tag1">[</b><b id="debug_var">' . '\\1' . '</b><b id="debug_tag1">]</b>', $out); //高亮变量
  572. $from = array(' ', '(', ')', '=>');
  573. $to = array(' ', '<b id="debug_tag2">(</i>', '<b id="debug_tag2">)</b>', '<b id="debug_set">=></b>');
  574. $out = str_replace($from, $to, $out);
  575. $keywords = array('Array', 'int', 'string', 'class', 'object', 'null'); //关键字高亮
  576. $keywords_to = $keywords;
  577. foreach($keywords as $key => $val) {
  578. $keywords_to[$key] = '<b id="debug_keywords">' . $val . '</b>';
  579. }
  580. $out = str_replace($keywords, $keywords_to, $out);
  581. $out = str_replace("\n\n", "\n", $out);
  582. echo $style . '<pre id="debug"><b id="debug_keywords">' . get_var_name($var) . '</b> = ' . $out . '</pre>';
  583. if ($exit) exit; //为真则退出
  584. }
  585. /**
  586. * 调试输出变量,对象的值。
  587. * 参数任意个(任意类型的变量)
  588. *
  589. * @return echo
  590. */
  591. function debug_out(){
  592. $avg_num = func_num_args();
  593. $avg_list = func_get_args();
  594. ob_start();
  595. for($i = 0; $i < $avg_num; $i++) {
  596. pr($avg_list[$i]);
  597. }
  598. $out = ob_get_clean();
  599. echo $out;
  600. exit;
  601. }
  602. /**
  603. * 取$from~$to范围内的随机数
  604. *
  605. * @param $from 下限
  606. * @param $to 上限
  607. * @return unknown_type
  608. */
  609. function rand_from_to($from, $to){
  610. $size = $from - $to; //数值区间
  611. $max = 30000; //最大
  612. if ($size < $max) {
  613. return $from + mt_rand(0, $size);
  614. } else {
  615. if ($size % $max) {
  616. return $from + random_from_to(0, $size / $max) * $max + mt_rand(0, $size % $max);
  617. } else {
  618. return $from + random_from_to(0, $size / $max) * $max + mt_rand(0, $max);
  619. }
  620. }
  621. }
  622. /**
  623. * 产生随机字串,可用来自动生成密码 默认长度6位 字母和数字混合
  624. *
  625. * @param string $len 长度
  626. * @param string $type 字串类型:0 字母 1 数字 2 大写字母 3 小写字母 4 中文
  627. * 其他为数字字母混合(去掉了 容易混淆的字符oOLl和数字01,)
  628. * @param string $addChars 额外字符
  629. * @return string
  630. */
  631. function rand_string($len = 4, $type='check_code'){
  632. $str = '';
  633. switch ($type) {
  634. case 0://大小写中英文
  635. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  636. break;
  637. case 1://数字
  638. $chars = str_repeat('0123456789', 3);
  639. break;
  640. case 2://大写字母
  641. $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  642. break;
  643. case 3://小写字母
  644. $chars = 'abcdefghijklmnopqrstuvwxyz';
  645. break;
  646. default:
  647. // 默认去掉了容易混淆的字符oOLl和数字01,要添加请使用addChars参数
  648. $chars = 'ABCDEFGHIJKMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789';
  649. break;
  650. }
  651. if ($len > 10) { // 位数过长重复字符串一定次数
  652. $chars = $type == 1 ? str_repeat($chars, $len) : str_repeat($chars, 5);
  653. }
  654. if ($type != 4) {
  655. $chars = str_shuffle($chars);
  656. $str = substr($chars, 0, $len);
  657. } else {
  658. // 中文随机字
  659. for($i = 0; $i < $len; $i ++) {
  660. $str .= msubstr($chars, floor(mt_rand(0, mb_strlen($chars, 'utf-8') - 1)), 1);
  661. }
  662. }
  663. return $str;
  664. }
  665. /**
  666. * 生成自动密码
  667. */
  668. function make_password(){
  669. $temp = '0123456789abcdefghijklmnopqrstuvwxyz'.
  670. 'ABCDEFGHIJKMNPQRSTUVWXYZ~!@#$^*)_+}{}[]|":;,.'.time();
  671. for($i=0;$i<10;$i++){
  672. $temp = str_shuffle($temp.substr($temp,-5));
  673. }
  674. return md5($temp);
  675. }
  676. /**
  677. * php DES解密函数
  678. *
  679. * @param string $key 密钥
  680. * @param string $encrypted 加密字符串
  681. * @return string
  682. */
  683. function des_decode($key, $encrypted){
  684. $encrypted = base64_decode($encrypted);
  685. $td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, ''); //使用MCRYPT_DES算法,cbc模式
  686. $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  687. $ks = mcrypt_enc_get_key_size($td);
  688. mcrypt_generic_init($td, $key, $key); //初始处理
  689. $decrypted = mdecrypt_generic($td, $encrypted); //解密
  690. mcrypt_generic_deinit($td); //结束
  691. mcrypt_module_close($td);
  692. return pkcs5_unpad($decrypted);
  693. }
  694. /**
  695. * php DES加密函数
  696. *
  697. * @param string $key 密钥
  698. * @param string $text 字符串
  699. * @return string
  700. */
  701. function des_encode($key, $text){
  702. $y = pkcs5_pad($text);
  703. $td = mcrypt_module_open(MCRYPT_DES, '', MCRYPT_MODE_CBC, ''); //使用MCRYPT_DES算法,cbc模式
  704. $ks = mcrypt_enc_get_key_size($td);
  705. mcrypt_generic_init($td, $key, $key); //初始处理
  706. $encrypted = mcrypt_generic($td, $y); //解密
  707. mcrypt_generic_deinit($td); //结束
  708. mcrypt_module_close($td);
  709. return base64_encode($encrypted);
  710. }
  711. function pkcs5_unpad($text){
  712. $pad = ord($text{strlen($text)-1});
  713. if ($pad > strlen($text)) return $text;
  714. if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return $text;
  715. return substr($text, 0, -1 * $pad);
  716. }
  717. function pkcs5_pad($text, $block = 8){
  718. $pad = $block - (strlen($text) % $block);
  719. return $text . str_repeat(chr($pad), $pad);
  720. }