Very practical code examples PHP 33

PHP for WEB developers is basically standard, other programmers could make up a few PHP code. Today, we summarize the 33 practical PHP code snippet, you can copy and paste directly when used, very convenient. It can also be used to enrich their own code base.

<PHP? 

/ **
* Time: 0000-00-00
* Author: xx
* super useful, must be the collection of PHP code samples
* /
class Helper {

/ **
*-friendly display var_dump
* /
static public function dump ($ var , $ echo = to true, $ label = null, $ strict = to true) {
$ label = ($ label === null) '?':. RTRIM ($ label) '';
! IF ($ strict) {
IF ( the ini_get ( 'html_errors')) {
$ Output = print_r ($ var, to true);
... $ Output = "<pre>" $ label htmlspecialchars ($ Output, ENT_QUOTES) "</ pre>";
} the else {
$ = $ label print_r Output ($ var, to true);.
}
} the else {
ob_start ();
var_dump ($ var);
$ ob_get_clean Output = ();
IF (extension_loaded ( '!xdebug')) {
$output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
$output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
}
}
if ($echo) {
echo $output;
return null;
} else
return $output;
}

/**
* 获取客户端IP地址
*/
static public function getClientIP() {
static $ip = NULL;
if ($ip !== NULL)
return $ip;
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown', $arr);
if (false !== $pos)
unset($arr[$pos]);
$ip = trim($arr[0]);
} ELSEIF (isset ($ _ SERVER [ 'HTTP_CLIENT_IP'])) {
$ IP = $ _SERVER [ 'HTTP_CLIENT_IP'];
} ELSEIF (isset ($ _ SERVER [ 'REMOTE_ADDR'])) {
$ IP = $ _SERVER [ 'REMOTE_ADDR' ];
}
// IP address of the legitimate verification
$ ip = (false == ip2long (ip $)!) $ ip: '0.0.0.0';?
return $ ip;
}

/ **
* create a directory loop
* /
static public function mkdir (the dir $, $ MODE = 0777) {
IF (is_dir ($ the dir) || @mkdir (the dir $, $ MODE))
return to true;
IF (mk_dir (dirname ($ the dir), $ MODE)!)
return to false ;
return @mkdir (the dir $, $ MODE);
}

/ **
* format unit
* /
static public function byteFormat ($ size, $ On Dec = 2) {
$ A = Array ( "B", "KB", "MB", "GB", "the TB", "PB");
$ POS = 0;
the while ($ size> = 1024) {
$ size / = 1024;
POS ++ $;
}
return round ($ size, $ On Dec) "" $ A [$ POS];..
}

/ **
* drop-down box, a radio button is automatically selected
*
* @param $ String input character
* @param $ param conditions
* @param $ type type
* Selected the checked
* @return String
* /
static public function Selected (String $, $ param =. 1, $ type = 'SELECT') {

IF (is_array ($ param)) {
$ = to true the in_array (String $, $ param);
} ELSEIF ($ String == $ param) {
$ = to true to true;
}
IF ($ to true)
$return = $type == 'select' ? 'selected="selected"' : 'checked="checked"';

echo $return;
}

/**
* 获得来源类型 post get
*
* @return unknown
*/
static public function method() {
return strtoupper(isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET' );
}

/**
* 提示信息
*/
static public function message($action = 'success', $content = '', $redirect = 'javascript:history.back(-1);', $timeout = 4) {

switch ($action) {
case 'success':
$titler = '操作完成';
$class = 'message_success';
$images = 'message_success.PNG '; $ = Titler' operation is not completed ';Case' error ':
BREAK;


$class = 'message_error';
$images = 'message_error.png';
break;
case 'errorBack':
$titler = '操作未完成';
$class = 'message_error';
$images = 'message_error.png';
break;
case 'redirect':
header("Location:$redirect");
break;
case 'script':
if (empty($redirect)) {
exit('<script language="javascript">alert("' . $content . '");window.history.back(-1)</script>');
} else {
exit('<script language="javascript">alert("' . $content . '");window.location=" ' . $redirect . ' "</script>');// message header}BREAK;
}




$header = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>操作提示</title>
<style type="text/css">
body{font:12px/1.7 "\5b8b\4f53",Tahoma;}
html,body,div,p,a,h3{margin:0;padding:0;}
.tips_wrap{ background:#F7FBFE;border:1px solid #DEEDF6;width:780px;padding:50px;margin:50px auto 0;}
.tips_inner{zoom:1;}
.tips_inner:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0;}
.tips_inner .tips_img{width:80px;float:left;}
.tips_info{float:left;line-height:35px;width:650px}
.tips_info h3{font-weight:bold;color:#1A90C1;font-size:16px;}
.tips_info p{font-size:14px;color:#999;}
.tips_info p.message_error{font-weight:bold;color:#F00;font-size:16px; line-height:22px}
.tips_info p.message_success{font-weight:bold;color:#1a90c1;font-size:16px; line-height:22px}
.tips_info p.return{font-size:12px}
.tips_info .time{color:#f00; font-size:14px; font-weight:bold}
.tips_info p a{color:#1A90C1;text-decoration:none;}
</style>
</head>

<body>';
// 信息底部
$footer = '</body></html>';

$body = '<script type="text/javascript">
function delayURL(url) {
var delay = document.getElementById("time").innerHTML;
//alert(delay);
if(delay > 0){
delay--;
document.getElementById("time").innerHTML = delay;
} else {
window.location.href = url;
}
setTimeout("delayURL(\'" + url + "\')", 1000);
}
</script><div class="tips_wrap">
<div class="tips_inner">
<div class="tips_img">
<img src="' . Yii::app()->baseUrl . '/static/images/' . $images . '"/>
</div>
<div class="tips_info">

<p class=" . $class . ">' . $content . '</p>
<p class="return">系统自动跳转在 <span class="time" id="time">' .$ timeout. '</ span> seconds, you do not want to wait, <a href="'. $redirect.'"> Click here to jump </a> </ the p-> </ div> <script type = "text</ div>
</ div>


delayURL("' . $redirect . '");
</script>';

exit($header . $body . $footer);
}

/**
* 查询字符生成
*/
static public function buildCondition(array $getArray, array $keys = array()) {
if ($getArray) {
foreach ($getArray as $key => $value) {
if (in_array($key, $keys) && $value) {
$arr[$key] = CHtml::encode(strip_tags($value));
}
}
return $arr;
}
}

/**
* base64_encode
*/
static function b64encode($string) {
$data = base64_encode($string);
$data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
return $data;
}

/**
* base64_decode
*/
static function b64decode($string) {
$data = str_replace(array('-', '_'), array('+', '/'), $string);
$mod4 = strlen($data) % 4;
if ($mod4) {
$data .= substr('====', $mod4);
}
return base64_decode($data);
}

/**
* 验证邮箱
*/
public static function email($str) {
if (empty($str))
return true;
$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
if (strpos($str, '@') !== false && strpos($str, '.') !== false) {
if (preg_match($chars, $str)) {
return true;
} else {
return false;
}
} else {
to false return;
}
}

/ **
* verified phone number
* /
public static function Mobile (STR $) {
IF (empty (STR $)) {
return to true;
}

return the preg_match ( '# 13 is ^ [\ D] {}. 9 $ | ^ 14 [0-9] \ D {. 8} | ^ 15 [0-9] \ {D}. 8 $ | ^ 18 is [0-9] \ {D} $ #. 8 ', STR $);
}

/ **
* fixed telephone verification
* /
public static function Tel (STR $) {
IF (empty (STR $)) {
return to true;
}
return the preg_match ( '/ ^ ((\ (\ D {2,3} \) ) | (\ d {3} \ -)) (\ (0 \ d {2,3} \) |?? 0 \ d {2,3} -) [1-9] \ d {6,7} ? (\ - \ D {l, 4}) $ / ', TRIM (STR $));
}

/ **
* verify qq number
* /
public static function qq (STR $) {
IF (empty (STR $)) {
return to true;
}

the preg_match return ( '/ ^ [1-9] \ D {4,12} $ /', TRIM (STR $));
}

/ **
* Verify ZIP
* /
public static function the zipCode (STR $) {
IF ( empty (STR $)) {
return to true;
}

return the preg_match ( '/ ^ [1-9] \ {D}. 5 $ /', TRIM (STR $));
}

/ **
* verify IP
* /
public static function IP (STR $) {
IF (empty (STR $))
return to true;

IF (the preg_match ( '# ^ \ D {l, 3} \ \ D {l, 3} \ \ D {l, 3}!.. . \ \ D} $ # {l, 3 ', STR $)) {
return to false;
}

$ = ip_array the explode (' ', $ STR);.

// ip address of each real number can not exceed 255 (0- 255)
return ($ ip_array [0] <= $ 255 && ip_array [. 1] <= $ 255 && ip_array [2] <= $ 255 && ip_array [. 3] <= 255) to true?:false;
}

/ **
* ID verification (China)
* /
public static function idCard (STR $) {
$ = TRIM STR (STR $);
IF (empty (STR $))
return to true;

IF (the preg_match ( "/ ^ ([ 0-9] {15} | [0-9]. 17 {} [0-9a-Z]) $ / I ", STR $))
return to true;
the else
return to false;
}

/ **
* verification URL
* /
public URL function static (STR $) {
IF (empty (STR $))
return to true;

return the preg_match ( '# (HTTP | HTTPS | FTP | FTPS):. // ([\ w to] + \) + [\ W ? -] + (/ [\ w-./?%&=]*)?#i ', $ STR) to true: to false;
}

/ **
* The location acquired IP
* @param $ IP
* return: IP , beginip, EndIP, Country, Area
* /
public static function getLocation (IP = $ '') {
$ip = new XIp();
$ipArr = $ip->getlocation($ip);
return $ipArr;
}

/**
* 中文转换为拼音
*/
public static function pinyin($str) {
$ip = new XPinyin();
return $ip->output($str);
}

/**
* 拆分sql
*
* @param $sql
*/
public static function splitsql($sql) {
$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=" . Yii::app()->db->charset, $sql);
$sql = str_replace("\r", "\n", $sql);
$ret = array();
$num = 0;
$queriesarray = explode(";\n", trim($sql));
unset($sql);
foreach ($queriesarray as $query) {
$ret[$num] = '';
$queries = explode("\n", trim($query));
$queries = array_filter($queries);
foreach ($queries as $query) {
$str1 = substr($query, 0, 1);
if ($str1 != '#' && $str1 != '-')
$ret[$num] .= $query;
}
$num++;
}
return ($ret);
}

/**
* 字符截取
*
* @param $string
* @param $length
* @param $dot
*/
public static function cutstr($string, $length, $dot = '...', $charset = 'utf-8') {
if (strlen($string) <= $length)
return $string;

$pre = chr(1);
$end = chr(1);
$string = str_replace(array('&', '"', '<', '>'), array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), $string);

$strcut = '';
if (strtolower($charset) == 'utf-8') {

$n = $tn = $noc = 0;
while ($n < strlen($string)) {

$t = ord($string[$n]);
if ($t == 9 || $t == 10 || ( 32 <= $t && $t <= 126 )) {
$tn = 1;
$n++;
$noc++;
} elseif (194 <= $t && $t <= 223) {
$tn = 2;
$n += 2;
$noc += 2;
} elseif (224 <= $t && $t <= 239) {
$tn = 3;
$n += 3;
$noc += 2;
} elseif (240 <= $t && $t <= 247) {
$tn = 4;
$n += 4;
$noc += 2;
} elseif (248 <= $t && $t <= 251) {
$tn = 5;
$n += 5;
$noc += 2;
} elseif ($t == 252 || $t == 253) {
$tn = 6;
$n += 6;
$noc += 2;
} else {
$n++;
}

if ($noc >= $length) {
break;
}
}
if ($noc > $length) {
$n -= $tn;
}

$strcut = substr($string, 0, $n);
} else {
for ($i = 0; $i < $length; $i++) {
$strcut .= ord($string[$i]) > 127 ? $string[$i] . $string[++$i] : $string[$i];
}
}

$strcut = str_replace(array($pre . '&' . $end, $pre . '"' . $end, $pre . '<' . $end, $pre . '>' . $end), array('&', '"', '<', '>'), $strcut);

strrpos POS = $ ($ strcut, CHR (. 1));
IF ($ POS to false ==!) {
$ strcut = substr ($ strcut, 0, $ POS);
}
return $ $ strcut DOT;.
}

/ **
description format *
* @param $ Subject
* /
public static function clearCutstr (Subject $, $ length = 0, DOT = $ '...', $ charset = 'UTF-. 8') {
IF ($ length) {
return :: cutstr xutils (the strip_tags (str_replace (Array ( "\ R & lt \ n-"), '', $ Subject)), $ length, DOT $, $ charset);
} the else {
return the strip_tags (str_replace (Array ( "\ R & lt \ n-"), '', $ Subject));
}
}

/ **
* English or detect whether a combination of alphanumeric
*
* Unknown @return
* /
public static function isEnglist ($ param) {
IF (! eregi ( "^ [A-Z0-9] $ {1,26}", $ param)) {
return to false;
} the else {
return to true;
}
}

/ **
* will automatically determine whether to raise the URL http: //
*
* @param $ HTTP
* @return String
* /
public static function convertHttp ($ URL) {
IF (URL == $ 'HTTP: //' || $ URL == '')
return '';

IF ( ! substr ($ URL, 0,. 7) = 'HTTP: //' && substr ($ URL, 0,. 8) = 'HTTPS: //')!
$ STR = 'HTTP: //' $ URL;.
the else
URL = STR $ $;
return $ STR;
}

/ *
heading style format
* /

public static function TitleStyle ($ style) {
$ text = '';
IF (style $ [ 'Bold'] == 'Y') {
$text .='font-weight:bold;';
$serialize['bold'] = 'Y';
}

if ($style['underline'] == 'Y') {
$text .='text-decoration:underline;';
$serialize['underline'] = 'Y';
}

if (!empty($style['color'])) {
$text .='color:#' . $style['color'] . ';';
$serialize['color'] = $style['color'];
}

return array('text' => $text, 'serialize' => empty($serialize) ? '' : serialize($serialize));
}

// 自动转换字符集 支持数组转换
static public function autoCharset($string, $from = 'gbk', $to = 'utf-8') {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($string) || (is_scalar($string) && !is_string($string))) {
//如果编码相同或者非字符串标量则不转换
return $string;
}
if (is_string($string)) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($string, $to, $from);
} elseif (function_exists('iconv')) {
return iconv($from, $to, $string);
} else {
return $string;
}
} elseif (is_array($string)) {
foreach ($string as $key => $val) {
$_key = self::autoCharset($key, $from, $to);
$string[$_key] = self::autoCharset($val, $from, $to);
if ($key != $_key)
unset($string[$key]);
}
return $string;
} else {
return $string;
}
}

/*
标题样式恢复
*/

public static function titleStyleRestore($serialize, $scope = 'bold') {
$unserialize = unserialize($serialize);
if ($unserialize['bold'] == 'Y' && $scope == 'bold')
return 'Y';
if ($unserialize['underline'] == 'Y' && $scope == 'underline')
return 'Y';
if ($unserialize['color'] && $scope == 'color')
return $unserialize['color'];IF (is_dir ($ dirname)) {$ Files = Array ();public static function GetDir ($ dirname) {* /* @return Unknown* @param $ dirname** listed in the folder list/ **
}










$fileHander = opendir($dirname);
while (( $file = readdir($fileHander) ) !== false) {
$filepath = $dirname . '/' . $file;
if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_file($filepath)) {
continue;
}
$files[] = self::autoCharset($file, 'GBK', 'UTF8');
}
closedir($fileHander);
} else {
$files = false;
}
return $files;
}

/**
* 列出文件列表
*
* @param $dirname
* @return unknown
*/
public static function getFile($dirname) {
$files = array();
if (is_dir($dirname)) {
$fileHander = opendir($dirname);
while (( $file = readdir($fileHander) ) !== false) {
$filepath = $dirname . '/' . $file;

if (strcmp($file, '.') == 0 || strcmp($file, '..') == 0 || is_dir($filepath)) {
continue;
}
$files[] = self::autoCharset($file, 'GBK', 'UTF8');
;
}
closedir($fileHander);
} else {
$files = false;
}
return $files;
}

/**
* [格式化图片列表数据]
*
* @return [type] [description]
*/
public static function imageListSerialize($data) {

foreach ((array) $data['file'] as $key => $row) {
if ($row) {
$var[$key]['fileId'] = $data['fileId'][$key];
$ var [$ key] [ '
}
}
return array('data' => $var, 'dataSerialize' => empty($var) ? '' : serialize($var));
}

/**
* 反引用一个引用字符串
* @param $string
* @return string
*/
static function stripslashes($string) {
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = self::stripslashes($val);
}
} else {
$string = stripslashes($string);
}
return $string;
}

/**
* 引用字符串
* @param $string
* @param $force
* @return string
*/
static function addslashes($string, $force = 1) {
if (is_array($string)) {
foreach ($string as $key => $val) {
$string[$key] = self::addslashes($val, $force);
}
} else {
$string = addslashes($string);
}
return $string;
}

/**
* 格式化内容
*/
static function formatHtml($content, $options = '') {
$purifier = new CHtmlPurifier();
if ($options != false)
$purifier->options = $options;
return $purifier->purify($content);
}

}

?>

 Source: Jingdezhen SEO

Guess you like

Origin www.cnblogs.com/1994jinnan/p/12239314.html