天天看点

33个超级有用必须要收藏的PHP代码样例

原文:http://blog.csdn.net/lmjy102/article/details/53540757

  1. <?php  
  2. class Helper {  
  3.     static public function dump($var, $echo = true, $label = null, $strict = true) {  
  4.         $label = ( $label === null ) ? '' : rtrim($label) . ' ';  
  5.         if (!$strict) {  
  6.             if (ini_get('html_errors')) {  
  7.                 $output = print_r($var, true);  
  8.                 $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";  
  9.             } else {  
  10.                 $output = $label . print_r($var, true);  
  11.             }  
  12.         } else {  
  13.             ob_start();  
  14.             var_dump($var);  
  15.             $output = ob_get_clean();  
  16.             if (!extension_loaded('xdebug')) {  
  17.                 $output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);  
  18.                 $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';  
  19.             }  
  20.         }  
  21.         if ($echo) {  
  22.             echo $output;  
  23.             return null;  
  24.         } else  
  25.             return $output;  
  26.     }  
  27.     static public function getClientIP() {  
  28.         static $ip = NULL;  
  29.         if ($ip !== NULL)  
  30.             return $ip;  
  31.         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {  
  32.             $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);  
  33.             $pos = array_search('unknown', $arr);  
  34.             if (false !== $pos)  
  35.                 unset($arr[$pos]);  
  36.             $ip = trim($arr[0]);  
  37.         } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {  
  38.             $ip = $_SERVER['HTTP_CLIENT_IP'];  
  39.         } elseif (isset($_SERVER['REMOTE_ADDR'])) {  
  40.             $ip = $_SERVER['REMOTE_ADDR'];  
  41.         }  
  42.         // IP地址合法验证  
  43.         $ip = ( false !== ip2long($ip) ) ? $ip : '0.0.0.0';  
  44.         return $ip;  
  45.     }  
  46.     static public function mkdir($dir, $mode = 0777) {  
  47.         if (is_dir($dir) || @mkdir($dir, $mode))  
  48.             return true;  
  49.         if (!mk_dir(dirname($dir), $mode))  
  50.             return false;  
  51.         return @mkdir($dir, $mode);  
  52.     }  
  53.     static public function byteFormat($size, $dec = 2) {  
  54.         $a = array("B", "KB", "MB", "GB", "TB", "PB");  
  55.         $pos = 0;  
  56.         while ($size >= 1024) {  
  57.             $size /= 1024;  
  58.             $pos++;  
  59.         }  
  60.         return round($size, $dec) . " " . $a[$pos];  
  61.     }  
  62.     static public function selected($string, $param = 1, $type = 'select') {  
  63.         if (is_array($param)) {  
  64.             $true = in_array($string, $param);  
  65.         } elseif ($string == $param) {  
  66.             $true = true;  
  67.         }  
  68.         if ($true)  
  69.             $return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';  
  70.         echo $return;  
  71.     }  
  72.     static public function method() {  
  73.         return strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' );  
  74.     }  
  75.     static public function message($action = 'success', $content = '', $redirect = 'javascript:history.back(-1);', $timeout = 4) {  
  76.         switch ($action) {  
  77.             case 'success':  
  78.                 $titler = '操作完成';  
  79.                 $class = 'message_success';  
  80.                 $images = 'message_success.png';  
  81.                 break;  
  82.             case 'error':  
  83.                 $titler = '操作未完成';  
  84.                 $class = 'message_error';  
  85.                 $images = 'message_error.png';  
  86.                 break;  
  87.             case 'errorBack':  
  88.                 $titler = '操作未完成';  
  89.                 $class = 'message_error';  
  90.                 $images = 'message_error.png';  
  91.                 break;  
  92.             case 'redirect':  
  93.                 header("Location:$redirect");  
  94.                 break;  
  95.             case 'script':  
  96.                 if (empty($redirect)) {  
  97.                     exit('<script language="javascript">alert("' . $content . '");window.history.back(-1)</script>');  
  98.                 } else {  
  99.                     exit('<script language="javascript">alert("' . $content . '");window.location=" ' . $redirect . '   "</script>');  
  100.                 }  
  101.                 break;  
  102.         }  
  103.         // 信息头部  
  104.         $header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  105. <html xmlns="http://www.w3.org/1999/xhtml">  
  106. <head>  
  107. <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  108. <title>操作提示</title>  
  109. <style type="text/css">  
  110. body{font:12px/1.7 "\5b8b\4f53",Tahoma;}  
  111. html,body,div,p,a,h3{margin:0;padding:0;}  
  112. .tips_wrap{ background:#F7FBFE;border:1px solid #DEEDF6;width:780px;padding:50px;margin:50px auto 0;}  
  113. .tips_inner{zoom:1;}  
  114. .tips_inner:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}  
  115. .tips_inner .tips_img{width:80px;float:left;}  
  116. .tips_info{float:left;line-height:35px;width:650px}  
  117. .tips_info h3{font-weight:bold;color:#1A90C1;font-size:16px;}  
  118. .tips_info p{font-size:14px;color:#999;}  
  119. .tips_info p.message_error{font-weight:bold;color:#F00;font-size:16px; line-height:22px}  
  120. .tips_info p.message_success{font-weight:bold;color:#1a90c1;font-size:16px; line-height:22px}  
  121. .tips_info p.return{font-size:12px}  
  122. .tips_info .time{color:#f00; font-size:14px; font-weight:bold}  
  123. .tips_info p a{color:#1A90C1;text-decoration:none;}  
  124. </style>  
  125. </head>  
  126. <body>';  
  127.         // 信息底部  
  128.         $footer = '</body></html>';  
  129.         $body = '<script type="text/javascript">  
  130.         function delayURL(url) {  
  131.         var delay = document.getElementById("time").innerHTML;  
  132.         //alert(delay);  
  133.         if(delay > 0){  
  134.         delay--;  
  135.         document.getElementById("time").innerHTML = delay;  
  136.     } else {  
  137.     window.location.href = url;  
  138.     }  
  139.     setTimeout("delayURL(\'" + url + "\')", 1000);  
  140.     }  
  141.     </script><div class="tips_wrap">  
  142.     <div class="tips_inner">  
  143.         <div class="tips_img">  
  144.             <img src="' . Yii::app()->baseUrl . '/static/images/' . $images . '"/>  
  145.         </div>  
  146.         <div class="tips_info">  
  147.             <p class="' . $class . '">' . $content . '</p>  
  148.             <p class="return">系统自动跳转在  <span class="time" id="time">' . $timeout . ' </span>  秒后,如果不想等待,<a href="' . $redirect . '">点击这里跳转</a></p>  
  149.         </div>  
  150.     </div>  
  151. </div><script type="text/javascript">  
  152.     delayURL("' . $redirect . '");  
  153.     </script>';  
  154.         exit($header . $body . $footer);  
  155.     }  
  156.     static public function buildCondition(array $getArray, array $keys = array()) {  
  157.         if ($getArray) {  
  158.             foreach ($getArray as $key => $value) {  
  159.                 if (in_array($key, $keys) && $value) {  
  160.                     $arr[$key] = CHtml::encode(strip_tags($value));  
  161.                 }  
  162.             }  
  163.             return $arr;  
  164.         }  
  165.     }  
  166.     static function b64encode($string) {  
  167.         $data = base64_encode($string);  
  168.         $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);  
  169.         return $data;  
  170.     }  
  171.     static function b64decode($string) {  
  172.         $data = str_replace(array('-', '_'), array('+', '/'), $string);  
  173.         $mod4 = strlen($data) % 4;  
  174.         if ($mod4) {  
  175.             $data .= substr('====', $mod4);  
  176.         }  
  177.         return base64_decode($data);  
  178.     }  
  179.     public static function email($str) {  
  180.         if (empty($str))  
  181.             return true;  
  182.         $chars = "/^([a-z0-9+_]|\\-|\\.)[email protected](([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";  
  183.         if (strpos($str, '@') !== false && strpos($str, '.') !== false) {  
  184.             if (preg_match($chars, $str)) {  
  185.                 return true;  
  186.             } else {  
  187.                 return false;  
  188.             }  
  189.         } else {  
  190.             return false;  
  191.         }  
  192.     }  
  193.     public static function mobile($str) {  
  194.         if (empty($str)) {  
  195.             return true;  
  196.         }  
  197.         return preg_match('#^13[\d]{9}$|14^[0-9]\d{8}|^15[0-9]\d{8}$|^18[0-9]\d{8}$#', $str);  
  198.     }  
  199.     public static function tel($str) {  
  200.         if (empty($str)) {  
  201.             return true;  
  202.         }  
  203.         return preg_match('/^((\d2,3\d2,3)|(\d{3}\-))?(0\d2,30\d2,3|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/', trim($str));  
  204.     }  
  205.     public static function qq($str) {  
  206.         if (empty($str)) {  
  207.             return true;  
  208.         }  
  209.         return preg_match('/^[1-9]\d{4,12}$/', trim($str));  
  210.     }  
  211.     public static function zipCode($str) {  
  212.         if (empty($str)) {  
  213.             return true;  
  214.         }  
  215.         return preg_match('/^[1-9]\d{5}$/', trim($str));  
  216.     }  
  217.     public static function ip($str) {  
  218.         if (empty($str))  
  219.             return true;  
  220.         if (!preg_match('#^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$#', $str)) {  
  221.             return false;  
  222.         }  
  223.         $ip_array = explode('.', $str);  
  224.         //真实的ip地址每个数字不能大于255(0-255)  
  225.         return ( $ip_array[0] <= 255 && $ip_array[1] <= 255 && $ip_array[2] <= 255 && $ip_array[3] <= 255 ) ? true : false;  
  226.     }  
  227.     public static function idCard($str) {  
  228.         $str = trim($str);  
  229.         if (empty($str))  
  230.             return true;  
  231.         if (preg_match("/^([0-9]{15}|[0-9]{17}[0-9a-z])$/i", $str))  
  232.             return true;  
  233.         else  
  234.             return false;  
  235.     }  
  236.     public static function url($str) {  
  237.         if (empty($str))  
  238.             return true;  
  239.         return preg_match('#(http|https|ftp|ftps)://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?#i', $str) ? true : false;  
  240.     }  
  241.     public static function getlocation($ip = '') {  
  242.         $ip = new XIp();  
  243.         $ipArr = $ip->getlocation($ip);  
  244.         return $ipArr;  
  245.     }  
  246.     public static function pinyin($str) {  
  247.         $ip = new XPinyin();  
  248.         return $ip->output($str);  
  249.     }  
  250.     public static function splitsql($sql) {  
  251.         $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=" . Yii::app()->db->charset, $sql);  
  252.         $sql = str_replace("\r", "\n", $sql);  
  253.         $ret = array();  
  254.         $num = 0;  
  255.         $queriesarray = explode(";\n", trim($sql));  
  256.         unset($sql);  
  257.         foreach ($queriesarray as $query) {  
  258.             $ret[$num] = '';  
  259.             $queries = explode("\n", trim($query));  
  260.             $queries = array_filter($queries);  
  261.             foreach ($queries as $query) {  
  262.                 $str1 = substr($query, 0, 1);  
  263.                 if ($str1 != '#' && $str1 != '-')  
  264.                     $ret[$num] .= $query;  
  265.             }  
  266.             $num++;  
  267.         }  
  268.         return ($ret);  
  269.     }  
  270.     public static function cutstr($string, $length, $dot = '...', $charset = 'utf-8') {  
  271.         if (strlen($string) <= $length)  
  272.             return $string;  
  273.         $pre = chr(1);  
  274.         $end = chr(1);  
  275.         $string = str_replace(array('&', '"', '<', '>'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);  
  276.         $strcut = '';  
  277.         if (strtolower($charset) == 'utf-8') {  
  278.             $n = $tn = $noc = 0;  
  279.             while ($n < strlen($string)) {  
  280.                 $t = ord($string[$n]);  
  281.                 if ($t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 )) {  
  282.                     $tn = 1;  
  283.                     $n++;  
  284.                     $noc++;  
  285.                 } elseif (194 <= $t && $t <= 223) {  
  286.                     $tn = 2;  
  287.                     $n += 2;  
  288.                     $noc += 2;  
  289.                 } elseif (224 <= $t && $t <= 239) {  
  290.                     $tn = 3;  
  291.                     $n += 3;  
  292.                     $noc += 2;  
  293.                 } elseif (240 <= $t && $t <= 247) {  
  294.                     $tn = 4;  
  295.                     $n += 4;  
  296.                     $noc += 2;  
  297.                 } elseif (248 <= $t && $t <= 251) {  
  298.                     $tn = 5;  
  299.                     $n += 5;  
  300.                     $noc += 2;  
  301.                 } elseif ($t == 252 || $t == 253) {  
  302.                     $tn = 6;  
  303.                     $n += 6;  
  304.                     $noc += 2;  
  305.                 } else {  
  306.                     $n++;  
  307.                 }  
  308.                 if ($noc >= $length) {  
  309.                     break;  
  310.                 }  
  311.             }  
  312.             if ($noc > $length) {  
  313.                 $n -= $tn;  
  314.             }  
  315.             $strcut = substr($string, 0, $n);  
  316.         } else {  
  317.             for ($i = 0; $i < $length; $i++) {  
  318.                 $strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];  
  319.             }  
  320.         }  
  321.         $strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&', '"', '<', '>'), $strcut);  
  322.         $pos = strrpos($strcut, chr(1));  
  323.         if ($pos !== false) {  
  324.             $strcut = substr($strcut, 0, $pos);  
  325.         }  
  326.         return $strcut . $dot;  
  327.     }  
  328.     public static function clearCutstr($subject, $length = 0, $dot = '...', $charset = 'utf-8') {  
  329.         if ($length) {  
  330.             return XUtils::cutstr(strip_tags(str_replace(array("\r\n"), '', $subject)), $length, $dot, $charset);  
  331.         } else {  
  332.             return strip_tags(str_replace(array("\r\n"), '', $subject));  
  333.         }  
  334.     }  
  335.     public static function isEnglist($param) {  
  336.         if (!eregi("^[A-Z0-9]{1,26}$", $param)) {  
  337.             return false;  
  338.         } else {  
  339.             return true;  
  340.         }  
  341.     }  
  342.     public static function convertHttp($url) {  
  343.         if ($url == 'http://' || $url == '')  
  344.             return '';  
  345.         if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://')  
  346.             $str = 'http://' . $url;  
  347.         else  
  348.             $str = $url;  
  349.         return $str;  
  350.     }  
  351.     public static function titleStyle($style) {  
  352.         $text = '';  
  353.         if ($style['bold'] == 'Y') {  
  354.             $text .='font-weight:bold;';  
  355.             $serialize['bold'] = 'Y';  
  356.         }  
  357.         if ($style['underline'] == 'Y') {  
  358.             $text .='text-decoration:underline;';  
  359.             $serialize['underline'] = 'Y';  
  360.         }  
  361.         if (!empty($style['color'])) {  
  362.             $text .='color:#' . $style['color'] . ';';  
  363.             $serialize['color'] = $style['color'];  
  364.         }  
  365.         return array('text' => $text, 'serialize' => empty($serialize) ? '' : serialize($serialize));  
  366.     }  
  367.     // 自动转换字符集 支持数组转换  
  368.     static public function autoCharset($string, $from = 'gbk', $to = 'utf-8') {  
  369.         $from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;  
  370.         $to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;  
  371.         if (strtoupper($from) === strtoupper($to) || empty($string) || (is_scalar($string) && !is_string($string))) {  
  372.             //如果编码相同或者非字符串标量则不转换  
  373.             return $string;  
  374.         }  
  375.         if (is_string($string)) {  
  376.             if (function_exists('mb_convert_encoding')) {  
  377.                 return mb_convert_encoding($string, $to, $from);  
  378.             } elseif (function_exists('iconv')) {  
  379.                 return iconv($from, $to, $string);  
  380.             } else {  
  381.                 return $string;  
  382.             }  
  383.         } elseif (is_array($string)) {  
  384.             foreach ($string as $key => $val) {  
  385.                 $_key = self::autoCharset($key, $from, $to);  
  386.                 $string[$_key] = self::autoCharset($val, $from, $to);  
  387.                 if ($key != $_key)  
  388.                     unset($string[$key]);  
  389.             }  
  390.             return $string;  
  391.         } else {  
  392.             return $string;  
  393.         }  
  394.     }  
  395.     public static function titleStyleRestore($serialize, $scope = 'bold') {  
  396.         $unserialize = unserialize($serialize);  
  397.         if ($unserialize['bold'] == 'Y' && $scope == 'bold')  
  398.             return 'Y';  
  399.         if ($unserialize['underline'] == 'Y' && $scope == 'underline')  
  400.             return 'Y';  
  401.         if ($unserialize['color'] && $scope == 'color')  
  402.             return $unserialize['color'];  
  403.     }  
  404.     public static function getDir($dirname) {  
  405.         $files = array();  
  406.         if (is_dir($dirname)) {  
  407.             $fileHander = opendir($dirname);  
  408.             while (( $file = readdir($fileHander) ) !== false) {  
  409.                 $filepath = $dirname . '/' . $file;  
  410.                 if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_file($filepath)) {  
  411.                     continue;  
  412.                 }  
  413.                 $files[] = self::autoCharset($file, 'GBK', 'UTF8');  
  414.             }  
  415.             closedir($fileHander);  
  416.         } else {  
  417.             $files = false;  
  418.         }  
  419.         return $files;  
  420.     }  
  421.     public static function getFile($dirname) {  
  422.         $files = array();  
  423.         if (is_dir($dirname)) {  
  424.             $fileHander = opendir($dirname);  
  425.             while (( $file = readdir($fileHander) ) !== false) {  
  426.                 $filepath = $dirname . '/' . $file;  
  427.                 if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_dir($filepath)) {  
  428.                     continue;  
  429.                 }  
  430.                 $files[] = self::autoCharset($file, 'GBK', 'UTF8');  
  431.                 ;  
  432.             }  
  433.             closedir($fileHander);  
  434.         } else {  
  435.             $files = false;  
  436.         }  
  437.         return $files;  
  438.     }  
  439.     public static function imageListSerialize($data) {  
  440.         foreach ((array) $data['file'] as $key => $row) {  
  441.             if ($row) {  
  442.                 $var[$key]['fileId'] = $data['fileId'][$key];  
  443.                 $var[$key]['file'] = $row;  
  444.             }  
  445.         }  
  446.         return array('data' => $var, 'dataSerialize' => empty($var) ? '' : serialize($var));  
  447.     }  
  448.     static function stripslashes($string) {  
  449.         if (is_array($string)) {  
  450.             foreach ($string as $key => $val) {  
  451.                 $string[$key] = self::stripslashes($val);  
  452.             }  
  453.         } else {  
  454.             $string = stripslashes($string);  
  455.         }  
  456.         return $string;  
  457.     }  
  458.     static function addslashes($string, $force = 1) {  
  459.         if (is_array($string)) {  
  460.             foreach ($string as $key => $val) {  
  461.                 $string[$key] = self::addslashes($val, $force);  
  462.             }  
  463.         } else {  
  464.             $string = addslashes($string);  
  465.         }  
  466.         return $string;  
  467.     }  
  468.     static function formatHtml($content, $options = '') {  
  469.         $purifier = new CHtmlPurifier();  
  470.         if ($options != false)  
  471.             $purifier->options = $options;  
  472.         return $purifier->purify($content);  
  473.     }  
  474. }  
  475. ?>