백엔드 개발 PHP 튜토리얼 내가 자주 사용하는 공통 함수 라이브러리

내가 자주 사용하는 공통 함수 라이브러리

Jul 25, 2016 am 09:09 AM

제로 패딩, 중국어 가로채기, 정지, html 점프, js 점프, html 필터링, 이메일 적법성 확인, 텍스트의 하이퍼링크를 클릭 가능한 연결로 변환, 시간 형식 반환 등과 같이 일반적으로 사용되는 PHP 함수 라이브러리가 있습니다.

  1. <?php
  2. //因为前后台TU要用到,所以放재supermario文件夹下方便중용
  3. /**
  4. * 아~ 귀여운 소수점~ 아~ 귀여운 천자리~
  5. * 4자리 이상이면 앞에 세 번째 자리를 추가하세요,
  6. * @param int $gold
  7. * @return 문자열
  8. */
  9. function showGold($gold) {
  10. return number_format($gold);
  11. }
  12. /**
  13. * 페이지 압축 출력
  14. */
  15. function ob_callback($buffer) {
  16. header('Etag: '.md5($buffer));
  17. if( Extension_loaded('zlib') AND strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip") ) {
  18. $buffer = gzencode($buffer,9);
  19. header('Content-Encoding: gzip');
  20. header('Vary: Accept-Encoding');
  21. //header('경유: www.guangxitravel .cn');
  22. header('콘텐츠 길이: '.strlen($buffer));
  23. }
  24. return $buffer;
  25. }
  26. /**
  27. * 프롬프트 없이 페이지로 이동
  28. * @param string $url
  29. * @param string $target
  30. */
  31. function go($url='', $target='parent') {
  32. if ($url != "") {
  33. echo('<script 언어="javascript" >window.location="' . $url . '";</script>');
  34. } else {
  35. echo('<script 언어="javascript">window.location=self .location;"</script>');
  36. }
  37. }
  38. /**
  39. * 清除缓存,ECHO,然后DIE(可恶的javascript php… ,总会有一些공자符…)
  40. * @param string $msg
  41. */
  42. function justSay($msg) {
  43. ob_clean();
  44. die($msg);
  45. }
  46. /**
  47. * 将符合第二个参数的第一个参数里的内容替换为红色
  48. * @param string $data
  49. * @param array $keyword
  50. * @return string
  51. */
  52. function change_keyword($data, $keywords) {
  53. if (is_array($keywords)) {
  54. foreach ($keywords as $k => $v) {
  55. $data = str_replace($v, '<span class="red b">' . $v . '</span>', $data);
  56. }
  57. return $data;
  58. } else {
  59. return str_replace($keywords, '<span class="red b">' . $keywords . '</span>', $data);
  60. }
  61. }
  62. /**
  63. * 创建完全随机的颜色
  64. * @return string
  65. */
  66. function makeColor() {
  67. $key = '#';
  68. for ($i = 0; $i < 6; $i++)
  69. $key.= rand(0, 9);//生成php随机数
  70. return $key;
  71. }
  72. /**
  73. * 自动加载模型和第三方功能类
  74. * @param string $className
  75. */
  76. function autoLoad($className) {
  77. if (strstr($_SERVER['REQUEST_URI'], "/operator/") == false) { //服务器不支持SCRIPT_URL
  78. if (file_exists(siteRoot . '/client/model/' . $className . '.php')) {
  79. require_once siteRoot . '/client/model/' . $className . '.php';
  80. return;
  81. }
  82. } else {
  83. if (file_exists(siteRoot . '/manager/model/' . $className . '.php')) {
  84. require_once siteRoot . '/manager/model/' . $className . '.php';
  85. return;
  86. }
  87. }
  88. if (file_exists(siteRoot . '/public/modules/' . $className . '.php')) {
  89. require_once siteRoot . '/public/modules/' . $className . '.php';
  90. return;
  91. }
  92. if (file_exists(siteRoot . '/client/order/model/' . $className . '.php')) {
  93. require_once siteRoot . '/client/order/model/' . $className . '.php';
  94. return;
  95. }
  96. }
  97. /**
  98. * 用javascript弹出一条信息
  99. * @param <string> $message
  100. */
  101. function message($message='') {
  102. echo('<script language="javascript">alert("' . $message . '");</script>');
  103. }
  104. /**
  105. * 模拟strstr()的第三个参数,返回$h中,$n之前的数据
  106. * //$h = haystack, $n = needle
  107. * @param <string> $h
  108. * @param <string> $n
  109. * @return <string>
  110. */
  111. function strstrb($h, $n) {
  112. return array_shift(explode($n, $h, 2));
  113. }
  114. /**
  115. * 显示错误信息,并跳转至$pageurl,含有样式
  116. *
  117. * @param string $messages
  118. * @param string $pageurl
  119. * @param int $msc 秒数
  120. */
  121. function msg($messages, $pageurl='javascript:history.back();', $msc=5) {
  122. echo '<title>System Message</title>
  123. <style type="text/css">
  124. *{margin:0;padding:0px}
  125. body{background:#fff;color:#333;font:12px Verdana, Tahoma, sans-serif;text-align:center;margin:0 auto;}
  126. a{text-decoration:none;color:#29458C}
  127. a:hover{text-decoration:underline;color:#f90}
  128. #msg{border:1px solid #c5d7ef;text-align:left;margin:10% auto; width:50%}
  129. #msgtitle{padding:5px 10px;background:#f0f6fb;border-bottom:1px #c5d7ef solid}
  130. #msgtitle h1{font-size:14px;font-weight:bold;padding-left:10px;border-left:3px solid #acb4be;color:#1f3a87}
  131. #msgcontent {padding:20px 50px;}
  132. #msgcontent li{display:block;padding:5px;list-style:none;}
  133. #msgcontent p{text-align:center;margin-top:10px;padding:0}
  134. </style>
  135. </head>
  136. <body>
  137. <div id="msg">
  138. <div id="msgtitle">
  139. <h1>Web System Message</h1>
  140. </div>
  141. <div id="msgcontent">
  142. ', $messages, '
  143. <p><a href="', $pageurl, '">>>>请点此处返回</a></p>
  144. </div>
  145. </div>
  146. <meta http-equiv="refresh" content="' . $msc . ';URL=', $pageurl, '">';
  147. exit();
  148. }
  149. /**
  150. * 检查后面的日期是否大于前面的日期
  151. * @param type $datecome 前面的日期
  152. * @param type $datego 后面的日期
  153. * @return type
  154. */
  155. function sub_date($datecome, $datego) {
  156. $d1 = strtotime($datecome);
  157. $d2 = strtotime($datego);
  158. $days = round(($d2 - $d1) / 3600 / 24);
  159. $days = $days < 1 ? 0 : $days;
  160. return $days;
  161. }
  162. /**
  163. * 将$string的$length后边的内容用$dot替换
  164. * @param string $string
  165. * @param int $length
  166. * @param string $dot
  167. * @return string
  168. */
  169. function cutstr($string, $length, $dot = '...') {
  170. @extract($string);
  171. if (strlen($string) <= $length) {
  172. return $string;
  173. }
  174. $string = htmlspecialchars($string);
  175. $string = str_replace(array('&amp;', '&quot;', '&lt;', '&gt;'), array('&', '"', '<', '>'), $string);
  176. $strcut = '';
  177. $n = $tn = $noc = 0;
  178. while ($n < strlen($string)) {
  179. $t = ord($string[$n]);
  180. if ($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
  181. $tn = 1;
  182. $n++;
  183. $noc++;
  184. } elseif (194 <= $t && $t <= 223) {
  185. $tn = 2;
  186. $n += 2;
  187. $noc += 2;
  188. } elseif (224 <= $t && $t < 239) {
  189. $tn = 3;
  190. $n += 3;
  191. $noc += 2;
  192. } elseif (240 <= $t && $t <= 247) {
  193. $tn = 4;
  194. $n += 4;
  195. $noc += 2;
  196. } elseif (248 <= $t && $t <= 251) {
  197. $tn = 5;
  198. $n += 5;
  199. $noc += 2;
  200. } elseif ($t == 252 || $t == 253) {
  201. $tn = 6;
  202. $n += 6;
  203. $noc += 2;
  204. } else {
  205. $n++;
  206. }
  207. if ($noc >= $length) {
  208. break;
  209. }
  210. }
  211. if ($noc > $length) {
  212. $n -= $tn;
  213. }
  214. $strcut = substr($string, 0, $n);
  215. $strcut = str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $strcut);
  216. return $strcut . $dot;
  217. }
  218. /**
  219. +----------------------------------------------------------
  220. * 如果 magic_quotes_gpc 为开启状态,则使用此方法使用为特殊符号前增加转移符号
  221. +----------------------------------------------------------
  222. * @access public
  223. +----------------------------------------------------------
  224. * @param string $value 可以为数组
  225. +----------------------------------------------------------
  226. * @return string
  227. +----------------------------------------------------------
  228. */
  229. function kaddslashes($value) {
  230. return $value = is_array($value) ? array_map('kaddslashes', $value) : addslashes($value);
  231. }
  232. /**
  233. +----------------------------------------------------------
  234. * 为特殊符号前去除转移符号
  235. +----------------------------------------------------------
  236. * @access public
  237. +----------------------------------------------------------
  238. * @param string $value 可以为数组
  239. +----------------------------------------------------------
  240. * @return string
  241. +----------------------------------------------------------
  242. */
  243. function kstripcslashes($value) {
  244. return $value = is_array($value) ? array_map('kstripcslashes', $value) : stripcslashes($value);
  245. }
  246. /**
  247. * 将字符串内容html实体化,避免一些非法信息直接执行。如果参数是数组,则递归。
  248. * @param string $value
  249. * @return array
  250. */
  251. function khtmlspecialchars($value) {
  252. return is_array($value) ? array_map('khtmlspecialchars', $value) :
  253. preg_replace('/&amp;((#(\d{3,5}|x[a-fA-F0-9]{4})|[a-zA-Z][a-z0-9]{2,5});)/', '&\\1', str_replace(array('&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $value));
  254. }
  255. /**
  256. * 将字符串中的html去除,如果参数是数组,则递归。
  257. * @param string $value
  258. * @return array
  259. */
  260. function Striptags($value) {
  261. return $value = is_array($value) ? array_map('striptags', $value) : Strip_tags($value);
  262. }
  263. /**
  264. * 이메일 유효성 확인
  265. *
  266. * @param string $email
  267. * @return bool
  268. */
  269. function check_email($email) {
  270. if (preg_match ("/([a-z0-9]*[-_.]?[a-z0-9] )*@([a-z0-9]*[-_]?[a-z0-9] ) [.][a-z]{2,3}([.][a-z]{2})?/i", $email)) {
  271. return true;
  272. } else {
  273. false 반환;
  274. }
  275. }
  276. /**
  277. * 보안 이메일 주소
  278. *
  279. * @param string $email
  280. * @param string $title
  281. * @param <type> $attributes
  282. * @return < ;
  283. */
  284. function safe_mailto($email, $title = '', $attributes = '') {
  285. if (is_array ($email)) {
  286. $tmp = $email;
  287. unset($email);
  288. extract($tmp);
  289. }
  290. $title = (문자열) $title;
  291. if ($title == "") {
  292. $title = $email;
  293. }
  294. for ($i = 0; $i < 16; $i ) {
  295. $x[] = substr('<a href="mailto:', $i, 1);
  296. }
  297. for ($i = 0; $i < strlen ($email); $i ) {
  298. $x[] = "|" . ord(substr($email, $i, 1));
  299. }
  300. $x[] = '"';
  301. if ($attributes != '') {
  302. if (is_array($attributes)) {
  303. foreach ($attributes as $key => $val) {
  304. $x[] = ' ' . $키 . '="';
  305. for ($i = 0; $i < strlen($val); $i ) {
  306. $x[] = "|" . ord(substr($val, $i , 1));
  307. }
  308. $x[] = '"';
  309. }
  310. } else {
  311. for ($i = 0; $i < strlen($attributes) ; $i ) {
  312. $x[] = substr($attributes, $i, 1);
  313. }
  314. }
  315. }
  316. $x[] = '> ';
  317. $temp = array();
  318. for ($i = 0; $i < strlen($title); $i ) {
  319. $ordinal = ord($title[ $i]);
  320. if ($ordinal < 128) {
  321. $x[] = "|" . $ordinal;
  322. } else {
  323. if (count($temp) == 0) {
  324. $count = ($ordinal < 224) ? 2 : 3;
  325. }
  326. $temp[] = $ordinal;
  327. if (count($temp) == $count) {
  328. $number = ($count == 3 ) ? (($temp['0'] % 16) * 4096) (($temp['1'] % 64) * 64) ($temp['2'] % 64) : (($temp['0' ] % 32) * 64) ($temp['1'] % 64);
  329. $x[] = "|" . $number;
  330. $count = 1;
  331. $temp = array();
  332. }
  333. }
  334. }
  335. $x[] = '<';
  336. $x[] = '/';
  337. $x[] = 'a';
  338. $x[] = '>';
  339. $x = array_reverse($x) ;
  340. ob_start();
  341. ?><script type="text/javascript">
  342. //<![CDATA[
  343. var l=new Array();
  344. <?php
  345. $i = 0;
  346. foreach ($x as $val) {
  347. ?>l[<?php echo $i ; ?>]='<?php echo $val; ?>';<?php } ?>
  348. for (var i = l.length-1; i >= 0; i=i-1){
  349. if (l[ i].substring(0, 1) == '|') document.write("" unescape(l[i].substring(1)) ";");
  350. else document.write(unescape( l[i]));}
  351. //]]>
  352. </script><?php
  353. $buffer = ob_get_contents();
  354. ob_end_clean();
  355. if ($tmp == '' || $tmp == NULL) {
  356. return $buffer;
  357. } else {
  358. echo $buffer;
  359. }
  360. }
  361. /**
  362. ---------------------------------- ----------
  363. * 텍스트의 하이퍼링크를 클릭 가능한 링크로 변환
  364. ---------- --- ---------------------------------
  365. * @access public
  366. ---- --- --------------------- --- -
  367. * @param string $text 처리할 문자열
  368. ------------- ------ -------
  369. * @return 문자열
  370. ---------- ---------- --------------
  371. */
  372. function makeLink($string) {
  373. $validChars = "a-z0-9/-_ =.~!%@?#&;:$|";
  374. $patterns = array(
  375. "/(^|[^]_a-z0-9-="'/])([a-z] ?)://([{$validChars}] )/ei",
  376. "/(^|[^]_a-z0-9-="'/])www.([a-z0-9-] ).([{$validChars}] )/ei",
  377. "/(^|[^]_a-z0-9-="'/])ftp.([a-z0-9-] ).([{$validChars}] )/ei",
  378. " /(^|[^]_a-z0-9-="'/:.])([a-z0-9-_.] ?)@([{$validChars}] )/ei");
  379. $replacements = array(
  380. "'\1<a href="\2://\3" title="\2://\3" rel="외부 ">\2://'.Input::truncate( '\3' ).'</a>'",
  381. "'\1<a href="http://www.\2 .\3" title="www.\2.\3" rel="external">'.Input::truncate( 'www.\2.\3' ).'</a>'",
  382. "'\1<a href="ftp://ftp.\2.\3" title="ftp.\2.\3" rel="external">'.Input::truncate( 'ftp .\2.\3' ).'</a>'",
  383. "'\1<a href="mailto:\2@\3" title="\2@\3">' .Input::truncate( '\2@\3' ).'</a>'");
  384. return preg_replace($patterns, $replacements, $string);
  385. }
  386. /**
  387. * 클라이언트 브라우저 가져오기
  388. * @return 문자열
  389. */
  390. function browser_info() {
  391. $browser = "";
  392. $browserver = "";
  393. $Browsers = array("Lynx", "MOSAIC" , "AOL", "Opera", "JAVA", "MacWeb", "WebExplorer", "OmniWeb");
  394. $Agent = $_SERVER["HTTP_USER_AGENT"] //浏览器的전체局变weight
  395. for ($i = 0; $i <= 7; $i ) {
  396. if (strpos($Agent, $Browsers[$i])) {
  397. $browser = $Browsers[$i];
  398. $browserver = "";
  399. }
  400. }
  401. if (ereg("Mozilla", $Agent) && ereg("MSIE", $Agent)) {
  402. $temp = 폭발 ("(", $Agent);
  403. $Part = $temp[1];
  404. $temp = 폭발(";", $Part);
  405. $Part = $temp[1];
  406. $temp = 폭발(" ", $Part);
  407. $browserver = $temp[2];
  408. //$browserver =preg_replace("/([d.] )/","1" ,$browserver);
  409. $browserver = "IE" . $browserver;
  410. $browser = "IE";
  411. }
  412. if (ereg("Mozilla", $Agent) && !ereg("MSIE", $Agent)) {
  413. $temp = 폭발("(", $Agent);
  414. $Part = $temp[0];
  415. $temp = 폭발("/", $Part);
  416. $browserver = $temp[1];
  417. $temp = 폭발(" ", $browserver);
  418. $browserver = $temp[0];
  419. $browserver = preg_replace("/([d.] )/", "1", $browserver);
  420. $browserver = " $browserver";
  421. $browser = "Netscape Navigator";
  422. }
  423. if (ereg("Mozilla", $Agent) && ereg( "Opera", $Agent)) {
  424. $temp = 폭발("(", $Agent);
  425. $Part = $temp[1];
  426. $temp = 폭발(")", $ 부분);
  427. $browserver = $temp[1];
  428. $temp = 폭발(" ", $browserver);
  429. $browserver = $temp[2];
  430. $browserver = preg_replace( "/([d.] )/", "1", $browserver);
  431. $browserver = " $browserver";
  432. $browser = "Opera";
  433. }
  434. //화狐浏览器
  435. if (ereg("Mozilla", $Agent) && ereg("Firefox", $Agent)) {
  436. $temp =explore("(", $Agent);
  437. $Part = $temp[1];
  438. $temp = 폭발(")", $Part);
  439. $browserver = $temp[1];
  440. $temp = 폭발(" ", $browserver);
  441. $browserver = $temp[2];
  442. $browser = "화염";
  443. }
  444. //谷歌浏览器
  445. if (ereg("Mozilla", $Agent) && ereg( "Chrome", $Agent)) {
  446. $temp = 폭발("(", $Agent);
  447. $temp = 폭발(" ", $temp[2]);
  448. $browserver = $ 온도['3']; //如果以后google升级不变位置的话就是它了
  449. $browser = "谷歌";
  450. }
  451. //360safe浏览器
  452. if (ereg("Mozilla", $Agent) && ereg("360SE", $Agent)) {
  453. //因为360浏览器,没有版本…
  454. $browserver = $browser = "360안전전卫士";
  455. }
  456. if ($browser != "") {
  457. //$browseinfo = $browser.$browserver;
  458. $ browserinfo = $browserver;
  459. } else {
  460. $browseinfo = "알 수 없음";
  461. }
  462. return $browseinfo;
  463. }
  464. /**
  465. * 返回时间格式
  466. * @name: prepareDate
  467. * @desc: 특정 데이터베이스 유형에 적합한 형식으로 날짜를 준비합니다
  468. * UNIX 타임스탬프가 제공됨
  469. * @param: $timestamp : UNIX 타임스탬프
  470. * @param: $fieldType: 날짜 형식을 지정하는 필드 유형
  471. * (MySQL에는 DATE, TIME, YEAR 및 DATETIME이 있습니다)
  472. */
  473. function prepareDate($timestamp, $fieldType = 'DATETIME') {
  474. $date = '';
  475. if (!$timestamp === false && $timestamp > 0) {
  476. 스위치 ($fieldType) {
  477. 케이스 'DATE' :
  478. $date = date('Y-m-d', $timestamp);
  479. break;
  480. 케이스 'TIME' :
  481. $date = date('H:i:s', $timestamp);
  482. break;
  483. case 'YEAR' :
  484. $date = date('Y', $timestamp);
  485. break;
  486. 기본값 :
  487. $date = date('Y-m-d H:i:s', $timestamp);
  488. break;
  489. }
  490. }
  491. return $date;
  492. }
  493. /**
  494. * 다차원 배열의 재귀에 적응하고 중복된 값을 제거하고 반환
  495. * @param array $array
  496. * @return array
  497. */
  498. function super_unique($array) {
  499. $result = array_map("unserialize", array_unique(array_map("serialize", $array))) ;
  500. foreach($result as $key => $value) {
  501. if (is_array($value)) {
  502. $result[$key] = super_unique($value);
  503. }
  504. }
  505. return $result;
  506. }
  507. /**
  508. * 값이 2자리를 충족하지 않으면 자동으로 0이 추가됩니다.
  509. * @param int $num
  510. * @return int
  511. */
  512. function fullzero($num){
  513. if(strlen($num)!=2){
  514. return '0' .$num;
  515. }else{
  516. return $num;
  517. }
  518. }
  519. //返回上一个url
  520. function get_visit_url(){
  521. return $ _SERVER['HTTP_REFERER'];
  522. }
  523. ?>
复代码
내가 자주 사용하는 공통 함수 라이브러리


본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

뜨거운 기사 태그

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) 11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄) Mar 03, 2025 am 10:49 AM

11 최고의 PHP URL 쇼트너 스크립트 (무료 및 프리미엄)

Instagram API 소개 Instagram API 소개 Mar 02, 2025 am 09:32 AM

Instagram API 소개

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel의 플래시 세션 데이터로 작업합니다

Laravel Back End : Part 2, React가있는 React 앱 구축 Laravel Back End : Part 2, React가있는 React 앱 구축 Mar 04, 2025 am 09:33 AM

Laravel Back End : Part 2, React가있는 React 앱 구축

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel 테스트에서 단순화 된 HTTP 응답 조롱

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트

라 라벨에서 알림 라 라벨에서 알림 Mar 04, 2025 am 09:22 AM

라 라벨에서 알림

See all articles