PHP代码样例

时间:2022-07-04 13:12:44
PHP代码样例PHP代码样例
  1 <?php
2
3 /**
4 * 时间:2015-8-6
5 * 作者:River
6 * 超级有用、必须收藏的PHP代码样例
7 */
8 class Helper {
9
10 /**
11 * 友好显示var_dump
12 */
13 static public function dump($var, $echo = true, $label = null, $strict = true) {
14 $label = ( $label === null ) ? '' : rtrim($label) . ' ';
15 if (!$strict) {
16 if (ini_get('html_errors')) {
17 $output = print_r($var, true);
18 $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
19 } else {
20 $output = $label . print_r($var, true);
21 }
22 } else {
23 ob_start();
24 var_dump($var);
25 $output = ob_get_clean();
26 if (!extension_loaded('xdebug')) {
27 $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
28 $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
29 }
30 }
31 if ($echo) {
32 echo $output;
33 return null;
34 } else
35 return $output;
36 }
37
38 /**
39 * 获取客户端IP地址
40 */
41 static public function getClientIP() {
42 static $ip = NULL;
43 if ($ip !== NULL)
44 return $ip;
45 if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
46 $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
47 $pos = array_search('unknown', $arr);
48 if (false !== $pos)
49 unset($arr[$pos]);
50 $ip = trim($arr[0]);
51 } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
52 $ip = $_SERVER['HTTP_CLIENT_IP'];
53 } elseif (isset($_SERVER['REMOTE_ADDR'])) {
54 $ip = $_SERVER['REMOTE_ADDR'];
55 }
56 // IP地址合法验证
57 $ip = ( false !== ip2long($ip) ) ? $ip : '0.0.0.0';
58 return $ip;
59 }
60
61 /**
62 * 循环创建目录
63 */
64 static public function mkdir($dir, $mode = 0777) {
65 if (is_dir($dir) || @mkdir($dir, $mode))
66 return true;
67 if (!mk_dir(dirname($dir), $mode))
68 return false;
69 return @mkdir($dir, $mode);
70 }
71
72 /**
73 * 格式化单位
74 */
75 static public function byteFormat($size, $dec = 2) {
76 $a = array("B", "KB", "MB", "GB", "TB", "PB");
77 $pos = 0;
78 while ($size >= 1024) {
79 $size /= 1024;
80 $pos++;
81 }
82 return round($size, $dec) . " " . $a[$pos];
83 }
84
85 /**
86 * 下拉框,单选按钮 自动选择
87 *
88 * @param $string 输入字符
89 * @param $param 条件
90 * @param $type 类型
91 * selected checked
92 * @return string
93 */
94 static public function selected($string, $param = 1, $type = 'select') {
95
96 if (is_array($param)) {
97 $true = in_array($string, $param);
98 } elseif ($string == $param) {
99 $true = true;
100 }
101 if ($true)
102 $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';
103
104 echo $return;
105 }
106
107 /**
108 * 获得来源类型 post get
109 *
110 * @return unknown
111 */
112 static public function method() {
113 return strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' );
114 }
115
116 /**
117 * 提示信息
118 */
119 static public function message($action = 'success', $content = '', $redirect = 'javascript:history.back(-1);', $timeout = 4) {
120
121 switch ($action) {
122 case 'success':
123 $titler = '操作完成';
124 $class = 'message_success';
125 $images = 'message_success.png';
126 break;
127 case 'error':
128 $titler = '操作未完成';
129 $class = 'message_error';
130 $images = 'message_error.png';
131 break;
132 case 'errorBack':
133 $titler = '操作未完成';
134 $class = 'message_error';
135 $images = 'message_error.png';
136 break;
137 case 'redirect':
138 header("Location:$redirect");
139 break;
140 case 'script':
141 if (empty($redirect)) {
142 exit('<script language="javascript">alert("' . $content . '");window.history.back(-1)</script>');
143 } else {
144 exit('<script language="javascript">alert("' . $content . '");window.location=" ' . $redirect . ' "</script>');
145 }
146 break;
147 }
148
149 // 信息头部
150 $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
151 <html xmlns="http://www.w3.org/1999/xhtml">
152 <head>
153 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
154 <title>操作提示</title>
155 <style type="text/css">
156 body{font:12px/1.7 "\5b8b\4f53",Tahoma;}
157 html,body,div,p,a,h3{margin:0;padding:0;}
158 .tips_wrap{ background:#F7FBFE;border:1px solid #DEEDF6;width:780px;padding:50px;margin:50px auto 0;}
159 .tips_inner{zoom:1;}
160 .tips_inner:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}
161 .tips_inner .tips_img{width:80px;float:left;}
162 .tips_info{float:left;line-height:35px;width:650px}
163 .tips_info h3{font-weight:bold;color:#1A90C1;font-size:16px;}
164 .tips_info p{font-size:14px;color:#999;}
165 .tips_info p.message_error{font-weight:bold;color:#F00;font-size:16px; line-height:22px}
166 .tips_info p.message_success{font-weight:bold;color:#1a90c1;font-size:16px; line-height:22px}
167 .tips_info p.return{font-size:12px}
168 .tips_info .time{color:#f00; font-size:14px; font-weight:bold}
169 .tips_info p a{color:#1A90C1;text-decoration:none;}
170 </style>
171 </head>
172 <body>';
173 // 信息底部
174 $footer = '</body></html>';
175
176 $body = '<script type="text/javascript">
177 function delayURL(url) {
178 var delay = document.getElementById("time").innerHTML;
179 //alert(delay);
180 if(delay > 0){
181 delay--;
182 document.getElementById("time").innerHTML = delay;
183 } else {
184 window.location.href = url;
185 }
186 setTimeout("delayURL(\'" + url + "\')", 1000);
187 }
188 </script><div class="tips_wrap">
189 <div class="tips_inner">
190 <div class="tips_img">
191 <img src="' . Yii::app()->baseUrl . '/static/images/' . $images . '"/>
192 </div>
193 <div class="tips_info">
194 <p class="' . $class . '">' . $content . '</p>
195 <p class="return">系统自动跳转在 <span class="time" id="time">' . $timeout . ' </span> 秒后,如果不想等待,<a href="' . $redirect . '">点击这里跳转</a></p>
196 </div>
197 </div>
198 </div><script type="text/javascript">
199 delayURL("' . $redirect . '");
200 </script>';
201
202 exit($header . $body . $footer);
203 }
204
205 /**
206 * 查询字符生成
207 */
208 static public function buildCondition(array $getArray, array $keys = array()) {
209 if ($getArray) {
210 foreach ($getArray as $key => $value) {
211 if (in_array($key, $keys) && $value) {
212 $arr[$key] = CHtml::encode(strip_tags($value));
213 }
214 }
215 return $arr;
216 }
217 }
218
219 /**
220 * base64_encode
221 */
222 static function b64encode($string) {
223 $data = base64_encode($string);
224 $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
225 return $data;
226 }
227
228 /**
229 * base64_decode
230 */
231 static function b64decode($string) {
232 $data = str_replace(array('-', '_'), array('+', '/'), $string);
233 $mod4 = strlen($data) % 4;
234 if ($mod4) {
235 $data .= substr('====', $mod4);
236 }
237 return base64_decode($data);
238 }
239
240 /**
241 * 验证邮箱
242 */
243 public static function email($str) {
244 if (empty($str))
245 return true;
246 $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
247 if (strpos($str, '@') !== false && strpos($str, '.') !== false) {
248 if (preg_match($chars, $str)) {
249 return true;
250 } else {
251 return false;
252 }
253 } else {
254 return false;
255 }
256 }
257
258 /**
259 * 验证手机号码
260 */
261 public static function mobile($str) {
262 if (empty($str)) {
263 return true;
264 }
265
266 return preg_match('#^13[\d]{9}$|14^[0-9]\d{8}|^15[0-9]\d{8}$|^18[0-9]\d{8}$#', $str);
267 }
268
269 /**
270 * 验证固定电话
271 */
272 public static function tel($str) {
273 if (empty($str)) {
274 return true;
275 }
276 return preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/', trim($str));
277 }
278
279 /**
280 * 验证qq号码
281 */
282 public static function qq($str) {
283 if (empty($str)) {
284 return true;
285 }
286
287 return preg_match('/^[1-9]\d{4,12}$/', trim($str));
288 }
289
290 /**
291 * 验证邮政编码
292 */
293 public static function zipCode($str) {
294 if (empty($str)) {
295 return true;
296 }
297
298 return preg_match('/^[1-9]\d{5}$/', trim($str));
299 }
300
301 /**
302 * 验证ip
303 */
304 public static function ip($str) {
305 if (empty($str))
306 return true;
307
308 if (!preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $str)) {
309 return false;
310 }
311
312 $ip_array = explode('.', $str);
313
314 //真实的ip地址每个数字不能大于255(0-255)
315 return ( $ip_array[0] <= 255 && $ip_array[1] <= 255 && $ip_array[2] <= 255 && $ip_array[3] <= 255 ) ? true : false;
316 }
317
318 /**
319 * 验证身份证(中国)
320 */
321 public static function idCard($str) {
322 $str = trim($str);
323 if (empty($str))
324 return true;
325
326 if (preg_match("/^([0-9]{15}|[0-9]{17}[0-9a-z])$/i", $str))
327 return true;
328 else
329 return false;
330 }
331
332 /**
333 * 验证网址
334 */
335 public static function url($str) {
336 if (empty($str))
337 return true;
338
339 return preg_match('#(http|https|ftp|ftps)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?#i', $str) ? true : false;
340 }
341
342 /**
343 * 根据ip获取地理位置
344 * @param $ip
345 * return :ip,beginip,endip,country,area
346 */
347 public static function getlocation($ip = '') {
348 $ip = new XIp();
349 $ipArr = $ip->getlocation($ip);
350 return $ipArr;
351 }
352
353 /**
354 * 中文转换为拼音
355 */
356 public static function pinyin($str) {
357 $ip = new XPinyin();
358 return $ip->output($str);
359 }
360
361 /**
362 * 拆分sql
363 *
364 * @param $sql
365 */
366 public static function splitsql($sql) {
367 $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=" . Yii::app()->db->charset, $sql);
368 $sql = str_replace("\r", "\n", $sql);
369 $ret = array();
370 $num = 0;
371 $queriesarray = explode(";\n", trim($sql));
372 unset($sql);
373 foreach ($queriesarray as $query) {
374 $ret[$num] = '';
375 $queries = explode("\n", trim($query));
376 $queries = array_filter($queries);
377 foreach ($queries as $query) {
378 $str1 = substr($query, 0, 1);
379 if ($str1 != '#' && $str1 != '-')
380 $ret[$num] .= $query;
381 }
382 $num++;
383 }
384 return ($ret);
385 }
386
387 /**
388 * 字符截取
389 *
390 * @param $string
391 * @param $length
392 * @param $dot
393 */
394 public static function cutstr($string, $length, $dot = '...', $charset = 'utf-8') {
395 if (strlen($string) <= $length)
396 return $string;
397
398 $pre = chr(1);
399 $end = chr(1);
400 $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);
401
402 $strcut = '';
403 if (strtolower($charset) == 'utf-8') {
404
405 $n = $tn = $noc = 0;
406 while ($n < strlen($string)) {
407
408 $t = ord($string[$n]);
409 if ($t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 )) {
410 $tn = 1;
411 $n++;
412 $noc++;
413 } elseif (194 <= $t && $t <= 223) {
414 $tn = 2;
415 $n += 2;
416 $noc += 2;
417 } elseif (224 <= $t && $t <= 239) {
418 $tn = 3;
419 $n += 3;
420 $noc += 2;
421 } elseif (240 <= $t && $t <= 247) {
422 $tn = 4;
423 $n += 4;
424 $noc += 2;
425 } elseif (248 <= $t && $t <= 251) {
426 $tn = 5;
427 $n += 5;
428 $noc += 2;
429 } elseif ($t == 252 || $t == 253) {
430 $tn = 6;
431 $n += 6;
432 $noc += 2;
433 } else {
434 $n++;
435 }
436
437 if ($noc >= $length) {
438 break;
439 }
440 }
441 if ($noc > $length) {
442 $n -= $tn;
443 }
444
445 $strcut = substr($string, 0, $n);
446 } else {
447 for ($i = 0; $i < $length; $i++) {
448 $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
449 }
450 }
451
452 $strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
453
454 $pos = strrpos($strcut, chr(1));
455 if ($pos !== false) {
456 $strcut = substr($strcut, 0, $pos);
457 }
458 return $strcut . $dot;
459 }
460
461 /**
462 * 描述格式化
463 * @param $subject
464 */
465 public static function clearCutstr($subject, $length = 0, $dot = '...', $charset = 'utf-8') {
466 if ($length) {
467 return XUtils::cutstr(strip_tags(str_replace(array("\r\n"), '', $subject)), $length, $dot, $charset);
468 } else {
469 return strip_tags(str_replace(array("\r\n"), '', $subject));
470 }
471 }
472
473 /**
474 * 检测是否为英文或英文数字的组合
475 *
476 * @return unknown
477 */
478 public static function isEnglist($param) {
479 if (!eregi("^[A-Z0-9]{1,26}$", $param)) {
480 return false;
481 } else {
482 return true;
483 }
484 }
485
486 /**
487 * 将自动判断网址是否加http://
488 *
489 * @param $http
490 * @return string
491 */
492 public static function convertHttp($url) {
493 if ($url == 'http://' || $url == '')
494 return '';
495
496 if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://')
497 $str = 'http://' . $url;
498 else
499 $str = $url;
500 return $str;
501 }
502
503 /*
504 标题样式格式化
505 */
506
507 public static function titleStyle($style) {
508 $text = '';
509 if ($style['bold'] == 'Y') {
510 $text .='font-weight:bold;';
511 $serialize['bold'] = 'Y';
512 }
513
514 if ($style['underline'] == 'Y') {
515 $text .='text-decoration:underline;';
516 $serialize['underline'] = 'Y';
517 }
518
519 if (!empty($style['color'])) {
520 $text .='color:#' . $style['color'] . ';';
521 $serialize['color'] = $style['color'];
522 }
523
524 return array('text' => $text, 'serialize' => empty($serialize) ? '' : serialize($serialize));
525 }
526
527 // 自动转换字符集 支持数组转换
528 static public function autoCharset($string, $from = 'gbk', $to = 'utf-8') {
529 $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
530 $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
531 if (strtoupper($from) === strtoupper($to) || empty($string) || (is_scalar($string) && !is_string($string))) {
532 //如果编码相同或者非字符串标量则不转换
533 return $string;
534 }
535 if (is_string($string)) {
536 if (function_exists('mb_convert_encoding')) {
537 return mb_convert_encoding($string, $to, $from);
538 } elseif (function_exists('iconv')) {
539 return iconv($from, $to, $string);
540 } else {
541 return $string;
542 }
543 } elseif (is_array($string)) {
544 foreach ($string as $key => $val) {
545 $_key = self::autoCharset($key, $from, $to);
546 $string[$_key] = self::autoCharset($val, $from, $to);
547 if ($key != $_key)
548 unset($string[$key]);
549 }
550 return $string;
551 } else {
552 return $string;
553 }
554 }
555
556 /*
557 标题样式恢复
558 */
559
560 public static function titleStyleRestore($serialize, $scope = 'bold') {
561 $unserialize = unserialize($serialize);
562 if ($unserialize['bold'] == 'Y' && $scope == 'bold')
563 return 'Y';
564 if ($unserialize['underline'] == 'Y' && $scope == 'underline')
565 return 'Y';
566 if ($unserialize['color'] && $scope == 'color')
567 return $unserialize['color'];
568 }
569
570 /**
571 * 列出文件夹列表
572 *
573 * @param $dirname
574 * @return unknown
575 */
576 public static function getDir($dirname) {
577 $files = array();
578 if (is_dir($dirname)) {
579 $fileHander = opendir($dirname);
580 while (( $file = readdir($fileHander) ) !== false) {
581 $filepath = $dirname . '/' . $file;
582 if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_file($filepath)) {
583 continue;
584 }
585 $files[] = self::autoCharset($file, 'GBK', 'UTF8');
586 }
587 closedir($fileHander);
588 } else {
589 $files = false;
590 }
591 return $files;
592 }
593
594 /**
595 * 列出文件列表
596 *
597 * @param $dirname
598 * @return unknown
599 */
600 public static function getFile($dirname) {
601 $files = array();
602 if (is_dir($dirname)) {
603 $fileHander = opendir($dirname);
604 while (( $file = readdir($fileHander) ) !== false) {
605 $filepath = $dirname . '/' . $file;
606
607 if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_dir($filepath)) {
608 continue;
609 }
610 $files[] = self::autoCharset($file, 'GBK', 'UTF8');
611 ;
612 }
613 closedir($fileHander);
614 } else {
615 $files = false;
616 }
617 return $files;
618 }
619
620 /**
621 * [格式化图片列表数据]
622 *
623 * @return [type] [description]
624 */
625 public static function imageListSerialize($data) {
626
627 foreach ((array) $data['file'] as $key => $row) {
628 if ($row) {
629 $var[$key]['fileId'] = $data['fileId'][$key];
630 $var[$key]['file'] = $row;
631 }
632 }
633 return array('data' => $var, 'dataSerialize' => empty($var) ? '' : serialize($var));
634 }
635
636 /**
637 * 反引用一个引用字符串
638 * @param $string
639 * @return string
640 */
641 static function stripslashes($string) {
642 if (is_array($string)) {
643 foreach ($string as $key => $val) {
644 $string[$key] = self::stripslashes($val);
645 }
646 } else {
647 $string = stripslashes($string);
648 }
649 return $string;
650 }
651
652 /**
653 * 引用字符串
654 * @param $string
655 * @param $force
656 * @return string
657 */
658 static function addslashes($string, $force = 1) {
659 if (is_array($string)) {
660 foreach ($string as $key => $val) {
661 $string[$key] = self::addslashes($val, $force);
662 }
663 } else {
664 $string = addslashes($string);
665 }
666 return $string;
667 }
668
669 /**
670 * 格式化内容
671 */
672 static function formatHtml($content, $options = '') {
673 $purifier = new CHtmlPurifier();
674 if ($options != false)
675 $purifier->options = $options;
676 return $purifier->purify($content);
677 }
678
679 }
680
681 ?>