php、yii通用globals方法
来源:互联网 发布:淘宝客做爆款 编辑:程序博客网 时间:2024/06/06 19:06
<?php
// 全局函数库
/**
* 获得当前的脚本网址
* return $nowurl;
* 将URL中的某参数设为某值
* @param $url 网址如:www.xxx.com/a.php?key=330
* @param $key 修改的参数
* @param $value 修改的值
* 获取IP
* return $nowurl;
*/
* 时间的增加
* @param $date 日期数据
* @param $int 要增加的数值
* @param $unit 增加的单位
*/
* 计算出给出的日期是星期几
* @param $date 日期数据
*/
* 检查日期是否合法日期
* @param $date 检查的日期
*/
* 检查时间是否合法时间
* @param $time 需要检查的时间
*/
* 时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天
* @param $date1 比较时间1
* @param $date2 比较时间2
* @param $unit 返回格式
*/
* 获取访问者浏览器
* 调用方法$browser=browseinfo() ;
* 直接返回结果
*/
* 获取访问者操作系统
* 调用方法$os=os_infor()
* 直接返回结果
*/
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
* 返回经stripslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
* 返回经addslashe处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
* 安全过滤函数
*
* @param $string
* @return string
*/
* 过滤ASCII码从0-28的控制字符
* @return String
*/
* 格式化文本域内容
*
* @param $string 文本域内容
* @return string
*/
* 将文本格式成适合js输出的字符串
* @param string $string 需要处理的字符串
* @param intval $isjs 是否执行字符串格式化,默认为执行
* @return string 处理后的字符串
*/
* 转义 javascript 代码标记
*
* @param $str
* @return mixed
*/
* 字符截取 支持UTF8/GBK
* @param $string
* @param $length
* @param $dot
*/
* 获取请求ip
* @return ip地址
*/
* 程序执行时间
*
* @returnint单位ms
*/
* 产生随机字符串
*
* @param int $length 输出长度
* @param string $chars 可选的 ,默认为 0123456789
* @return string 字符串
*/
* 将字符串转换为数组
*
* @paramstring$data字符串
* @returnarray返回数组格式,如果,data为空,则返回空数组
*/
* 将数组转换为字符串
*
* @paramarray$data数组
* @parambool$isformdata如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @returnstring返回字符串,如果,data为空,则返回空
*/
* 转换字节数为其他单位
*
*
* @paramstring$filesize字节大小
* @returnstring返回大小
*/
* 查询字符是否存在于某字符串
*
* @param $haystack 字符串
* @param $needle 要查找的字符
* @return bool
*/
* 取得文件扩展
*
* @param $filename 文件名
* @return 扩展名
*/
* 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
* @param $data 条件数组或者字符串
* @param $front 连接符
* @param $in_column 字段名称
* @return string
*/
* 判断email格式是否正确
* @param $email
*/
* 文件下载
* @param $filepath 文件路径
* @param $filename 文件名称
*/
* 判断字符串是否为utf8编码,英文和半角字符返回ture
* @param $string
* @return bool
*/
* 对用户的密码进行加密
* @param $password
* @param $encrypt //传入加密串,在修改密码时做认证
* @return array/password
*/
* 生成随机字符串
* @param string $lenth 长度
* @return string 字符串
*/
* 检查密码长度是否符合规定
*
* @param STRING $password
* @return TRUE or FALSE
*/
* 检测输入中是否含有错误字符
*
* @param char $string 要检查的字符串名称
* @return TRUE or FALSE
*/
* 检查用户名是否符合规定
*
* @param STRING $username 要检查的用户名
* @return TRUE or FALSE
*/
* 检查id是否存在于数组中
*
* @param $id
* @param $ids
* @param $s
*/
* 对数据进行编码转换
* @param array/string $data 数组
* @param string $input 需要转换的编码
* @param string $output 转换后的编码
*/
* 函数:get_magic_quotes_gpc在OFF状态下处理字符串的函数.
* @param string $arr 需要处理的字符串
*/
* 表单验证的函数
* @param $form_vars 数组
*/
* js中的escape及unescape函数的php实现
* 在用js传递数据的时候经常会用到的!
*/
* 返回最佳图片的高度,宽度。以及原来的高度和宽度
* @param $ImgFile 图片地址
* @param $ImgW 需要处理的图片宽度
* @param $ImgH 需要处理的图片高度
* @param $SrcH 原高度
* @param $SrcW 原宽度
* @param $DstH 目标高度
* @param $DstW 目标宽度
* 调用时用 list($SrcW,$SrcH,$DstW,$DstH) = RtImageSize($ImgFile,200,200)
*/
* 防止表单被重复提交的函数
* 注意:用submit_table()函数之前不能有任何输出
*
* @param string $get_name 提交(submit)过来的变量名称
* @param string $var_name 用来存储$get_name内容的变量名
* @return boolean
*
* 用例:
* if(submit_table('t1'))echo $t1;
* else echo " 已提交过!";
*
*/
* 插入规定大小范围的图片
* @param string $imagePath 图片路径
* @param int $w 图片的宽
* @param int $h 图片的高
* @return string 图片标签
*/
*把全角数字转为半角数字
* @param string $fnum 转换的数字串
*/
* 去除HTML标记
* @param string $txt 需要处理的代码
*/
* 读取文件函数
* @param string $file_name 文件名字
*/
* 写文件
* @param $file 文件名字
* @param $cont 内容
* @param $mod 模式
*/
* 301 重定向
* 用于非目录向目录重定向
* @param $url 重定向网址
* @param $time 重定时间
*/
* 定时跳转重定向
* 用于非目录向目录重定向
* @param $url 重定向网址
* @param $time 重定时间
*/
* AJAX廷时重定向
* @param $url 跳转URL
* @param $time 廷时秒数
* @param $space
* */
* 主要是用来替换关键词 如:关键字加粗加红
* @param $isreplace 查找的值 数组
* @param $replace 替换 $isreplace 中的值的值 数组
* @param $str 要处理的字符串
*/
* 清除数据两边的多余空格
*
* @param $data 要进行处理的数据
*/
* 过滤掉链接中所有非本站的网址链接
* @param $str 要进行过滤的HTML内容
*_DOMAIN_NAME_ 请自行定义
*/
* 计算百分比
* @param $total 总数
* @param $num 基数
* @param $len 小数点长度
*/
* 通过邮箱地址,返回邮箱的登陆网址
* @param $email 邮箱地址
*/
* 验证码
* @param int $num 字符个数
* @param int $size 字符大小
* @param int $width 验证码宽度
* @param int $height 决验证码高度
* @放一个font.ttf 字体到目录下
* @调用方法:vCode(4,20,100,50);
*/
* 获取百度的热词
* @return array 返回百度的热词数据(数组返回)
*/
*
* getOptions 参数列表:
* - result Options 数组
* - vals Options 数组修改的键值 (Value)
* - except Options 除"except"值外的数据调用
* - same Value和Title 值是否相同
* - exceptKey Options 除"exceptKey"键外的数据调用
*
* @return Array() $options
*/
*
* getRadios 参数列表:
* - result Radio 数组
* - name Radio 名字
* - checked 默认选中第一个,通读索引控制 Radio 的 Checked 状态
* - vals 通过VALUE控制 Radio 的 Checked 状态
* - except Radios 除"except"值外的数据调用
* - enter 换行参数
* - Events 事件参数
* - style 样式参数
* - disabled 显示参数
* - exceptKey Radios 除"exceptKey"键外的数据调用
*
* @return Array() $radios
*/
*
* getCheckboxs 参数列表:
* - result Checkbox 数组
* - name Checkbox 名字
* - checked 默认选中第一个,通读索引控制 Checkbox 的 Checked 状态
* - vals 通过VALUE控制 Checkbox 的 Checked 状态
* - except Checkboxs 除"except"值外的数据调用
* - enter 换行参数
* - Events 事件参数
* - style 样式参数
* - disabled 显示参数
* - exceptKey Checkboxs 除"exceptKey"键外的数据调用
*
* @return Array() $Checkboxs
*/
* 数组重建索引
* */
* 简化findall数据
* */
* 获取会员存储在cookie里面的ID
* */
* This is the shortcut to Yii::app()
*/
* This is the shortcut to Yii::app()->clientScript
*/
* 加载JS
*/
* 加载JS
*/
* 加载CSS
*/
* This is the shortcut to Yii::app()->user.
*/
* This is the shortcut to Yii::app()->createUrl()
*/
* 创建绝对地址
* This is the shortcut to Yii::app()->createAbsoluteUrl()
*/
* This is the shortcut to CHtml::encode
*/
* This is the shortcut to CHtml::link()
*/
* This is the shortcut to Yii::t() with default category = 'stay'
*/
* This is the shortcut to Yii::app()->request->baseUrl
* If the parameter is given, it will be returned and prefixed with the app baseUrl.
*/
* Returns the named application parameter.
* This is the shortcut to Yii::app()->params[$name].
*/
* Dump as many variables as you want. Infinite parameters.
*/
* @return string the generated image tag
*/
* 信息提示
* @param string $message 提示内容
* @param int $type 类型
* @param string $status 状态:success 成功,error 错误
* @param array $link
* @return array
*/
* 将XML转为ARRAY
* @param string $data XML数据
* @return array
*/
* 将ARRAY转为XML
* @param array $arr ARRAY数据
* @param int $dom ARRAY数据
* @param int $item ARRAY数据
* @param string/array $element ARRAY数据
* @return array
*/
* 将json转为XML
* @param string $source json数据
* @param string $charset 编码
* @return array
*/
* 生成指定的客服链接
* @param string $id 号码
* @param int $type 客服类型:1:qq,2:MSN 3旺旺
* @return string
*/
* 把数组加密为URL可传递的字符串,只支持一维数组
* @param array $params
* @return string
*/
* 把URL加密串解密,返回数组
* @param string $hash
* @return array
*/
* 得到新订单号
* @return string
*/
* 货币格式化
*/
?>
// 全局函数库
/**
* 获得当前的脚本网址
* return $nowurl;
*/
function GetCurUrl(){if(!empty($_SERVER["REQUEST_URI"])){$scriptName = $_SERVER["REQUEST_URI"];$nowurl = $scriptName;}else{$scriptName = $_SERVER["PHP_SELF"];if(empty($_SERVER["QUERY_STRING"])){$nowurl = $scriptName;}else{$nowurl = $scriptName."?".$_SERVER["QUERY_STRING"];}}return $nowurl;}/**
* 将URL中的某参数设为某值
* @param $url 网址如:www.xxx.com/a.php?key=330
* @param $key 修改的参数
* @param $value 修改的值
*/
function url_set_value($url,$key,$value){$a=explode('?',$url);$url_f=$a[0];$query=$a[1];parse_str($query,$arr);$arr[$key]=$value;return $url_f.'?'.http_build_query($arr);}/**
* 获取IP
* return $nowurl;
*/
function GetIP() { if ($_SERVER["HTTP_X_FORWARDED_FOR"]) $ip = $_SERVER["HTTP_X_FORWARDED_FOR"]; else if ($_SERVER["HTTP_CLIENT_IP"]) $ip = $_SERVER["HTTP_CLIENT_IP"]; else if ($_SERVER["REMOTE_ADDR"]) $ip = $_SERVER["REMOTE_ADDR"]; else if (getenv("HTTP_X_FORWARDED_FOR")) $ip = getenv("HTTP_X_FORWARDED_FOR"); else if (getenv("HTTP_CLIENT_IP")) $ip = getenv("HTTP_CLIENT_IP"); else if (getenv("REMOTE_ADDR")) $ip = getenv("REMOTE_ADDR"); else $ip = "Unknown"; return $ip;}/**
* 时间的增加
* @param $date 日期数据
* @param $int 要增加的数值
* @param $unit 增加的单位
*/
function DateAdd($date, $int, $unit = "d") { $dateArr = explode("-", $date); $value[$unit] = $int; return date("Y-m-d", mktime(0,0,0, $dateArr[1] + $value['m'], $dateArr[2] + $value['d'], $dateArr[0] + $value['y']));}/**
* 计算出给出的日期是星期几
* @param $date 日期数据
*/
function GetWeekDay($date) { $dateArr = explode("-", $date); return date("w", mktime(0,0,0,$dateArr[1],$dateArr[2],$dateArr[0]));}/**
* 检查日期是否合法日期
* @param $date 检查的日期
*/
function check_date($date) { $dateArr = explode("-", $date); if (is_numeric($dateArr[0]) && is_numeric($dateArr[1]) && is_numeric($dateArr[2])) { return checkdate($dateArr[1],$dateArr[2],$dateArr[0]); } return false;}/**
* 检查时间是否合法时间
* @param $time 需要检查的时间
*/
function check_time($time) { $timeArr = explode(":", $time); if (is_numeric($timeArr[0]) && is_numeric($timeArr[1]) && is_numeric($timeArr[2])) { if (($timeArr[0] >= 0 && $timeArr[0] <= 23) && ($timeArr[1] >= 0 && $timeArr[1] <= 59) && ($timeArr[2] >= 0 && $timeArr[2] <= 59)) return true; else return false; } return false;}/**
* 时间比较函数,返回两个日期相差几秒、几分钟、几小时或几天
* @param $date1 比较时间1
* @param $date2 比较时间2
* @param $unit 返回格式
*/
function DateDiff($date1, $date2, $unit = "") { switch ($unit) { case 's': $dividend = 1; break; case 'i': $dividend = 60; break; case 'h': $dividend = 3600; break; case 'd': $dividend = 86400; break; default: $dividend = 86400; } $time1 = strtotime($date1); $time2 = strtotime($date2); if ($time1 && $time2) return (float)($time1 - $time2) / $dividend; return false;}/**
* 获取访问者浏览器
* 调用方法$browser=browseinfo() ;
* 直接返回结果
*/
function browse_infor(){$browser="";$browserver="";$Browsers =array("Lynx","MOSAIC","AOL","Opera","JAVA","MacWeb","WebExplorer","OmniWeb");$Agent = $GLOBALS["HTTP_USER_AGENT"];for ($i=0; $i<=7; $i++){if (strpos($Agent,$Browsers[$i])){$browser = $Browsers[$i];$browserver ="";}}if (ereg("Mozilla",$Agent) && !ereg("MSIE",$Agent)){$temp =explode("(", $Agent); $Part=$temp[0];$temp =explode("/", $Part); $browserver=$temp[1];$temp =explode(" ",$browserver); $browserver=$temp[0];$browserver =preg_replace("/([d.]+)/","1",$browserver);$browserver = " $browserver";$browser = "Netscape Navigator";}if (ereg("Mozilla",$Agent) && ereg("Opera",$Agent)){$temp =explode("(", $Agent); $Part=$temp[1];$temp =explode(")", $Part); $browserver=$temp[1];$temp =explode(" ",$browserver);$browserver=$temp[2];$browserver =preg_replace("/([d.]+)/","1",$browserver);$browserver = " $browserver";$browser = "Opera";}if (ereg("Mozilla",$Agent) && ereg("MSIE",$Agent)){$temp = explode("(", $Agent); $Part=$temp[1];$temp = explode(";",$Part); $Part=$temp[1];$temp = explode(" ",$Part);$browserver=$temp[2];$browserver =preg_replace("/([d.]+)/","1",$browserver);$browserver = " $browserver";$browser = "Internet Explorer";}if ($browser!=""){$browseinfo = "$browser$browserver";}else{$browseinfo = "Unknown";}return $browseinfo;}/**
* 获取访问者操作系统
* 调用方法$os=os_infor()
* 直接返回结果
*/
function osinfo() {$os="";$Agent = $GLOBALS["HTTP_USER_AGENT"];if (eregi('win',$Agent) && strpos($Agent, '95')) {$os="Windows 95";}elseif (eregi('win 9x',$Agent) && strpos($Agent, '4.90')) {$os="Windows ME";}elseif (eregi('win',$Agent) && ereg('98',$Agent)) {$os="Windows 98";}elseif (eregi('win',$Agent) && eregi('nt 5.0',$Agent)) {$os="Windows 2000";}elseif (eregi('win',$Agent) && eregi('nt',$Agent)) {$os="Windows NT";}elseif (eregi('win',$Agent) && eregi('nt 5.1',$Agent)) {$os="Windows XP";}elseif (eregi('win',$Agent) && ereg('32',$Agent)) {$os="Windows 32";}elseif (eregi('linux',$Agent)) {$os="Linux";}elseif (eregi('unix',$Agent)) {$os="Unix";}elseif (eregi('sun',$Agent) && eregi('os',$Agent)) {$os="SunOS";}elseif (eregi('ibm',$Agent) && eregi('os',$Agent)) {$os="IBM OS/2";}elseif (eregi('Mac',$Agent) && eregi('PC',$Agent)) {$os="Macintosh";}elseif (eregi('PowerPC',$Agent)) {$os="PowerPC";}elseif (eregi('AIX',$Agent)) {$os="AIX";}elseif (eregi('HPUX',$Agent)) {$os="HPUX";}elseif (eregi('NetBSD',$Agent)) {$os="NetBSD";}elseif (eregi('BSD',$Agent)) {$os="BSD";}elseif (ereg('OSF1',$Agent)) {$os="OSF1";}elseif (ereg('IRIX',$Agent)) {$os="IRIX";}elseif (eregi('FreeBSD',$Agent)) {$os="FreeBSD";}if ($os=='') $os = "Unknown";return $os;}/**
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_addslashes($string){if(!is_array($string)) return addslashes($string);foreach($string as $key => $val) $string[$key] = new_addslashes($val);return $string;}/**
* 返回经stripslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_stripslashes($string) {if(!is_array($string)) return stripslashes($string);foreach($string as $key => $val) $string[$key] = new_stripslashes($val);return $string;}/**
* 返回经addslashe处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
function new_html_special_chars($string) {if(!is_array($string)) return htmlspecialchars($string);foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);return $string;}/**
* 安全过滤函数
*
* @param $string
* @return string
*/
function safe_replace($string) {$string = str_replace('%20','',$string);$string = str_replace('%27','',$string);$string = str_replace('%2527','',$string);$string = str_replace('*','',$string);$string = str_replace('"','"',$string);$string = str_replace("'",'',$string);$string = str_replace('"','',$string);$string = str_replace(';','',$string);$string = str_replace('<','<',$string);$string = str_replace('>','>',$string);$string = str_replace("{",'',$string);$string = str_replace('}','',$string);return $string;}/**
* 过滤ASCII码从0-28的控制字符
* @return String
*/
function trim_unsafe_control_chars($str) {$rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );}/**
* 格式化文本域内容
*
* @param $string 文本域内容
* @return string
*/
function trim_textarea($string) {$string = nl2br ( str_replace ( ' ', ' ', $string ) );return $string;}/**
* 将文本格式成适合js输出的字符串
* @param string $string 需要处理的字符串
* @param intval $isjs 是否执行字符串格式化,默认为执行
* @return string 处理后的字符串
*/
function format_js($string, $isjs = 1){$string = addslashes(str_replace(array("\r", "\n"), array('', ''), $string));return $isjs ? 'document.write("'.$string.'");' : $string;}/**
* 转义 javascript 代码标记
*
* @param $str
* @return mixed
*/
function trim_script($str) {$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '<\\1script\\2>', $str );$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '<\\1iframe\\2>', $str );$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '<\\1frame\\2>', $str );$str = preg_replace ( '/]]\>/si', ']] >', $str );return $str;}/**
* 字符截取 支持UTF8/GBK
* @param $string
* @param $length
* @param $dot
*/
function str_cut($string, $length, $dot = '') {$CHARSET = Yii::app()->charset;$strlen = strlen($string);if($strlen <= $length) return $string;$string = str_replace(array(' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array(' ',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);$strcut = '';if(strtolower($CHARSET) == 'utf-8') {$length = intval($length-strlen($dot)-$length/3);$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);$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);}else {$dotlen = strlen($dot);$maxi = $length - $dotlen - 1;$current_str = '';$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');$replace_arr = array('&',' ', '"', ''', '“', '”', '—', '<', '>', '·', '…',' ');$search_flip = array_flip($search_arr);for ($i = 0; $i < $maxi; $i++) {$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];if (in_array($current_str, $search_arr)) {$key = $search_flip[$current_str];$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);}$strcut .= $current_str;}}return $strcut.$dot;}/**
* 获取请求ip
* @return ip地址
*/
function ip() {if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {$ip = getenv('HTTP_CLIENT_IP');} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {$ip = getenv('HTTP_X_FORWARDED_FOR');} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {$ip = getenv('REMOTE_ADDR');} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {$ip = $_SERVER['REMOTE_ADDR'];}return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';}/**
* 程序执行时间
*
* @returnint单位ms
*/
function execute_time() {$stime = explode ( ' ', SYS_START_TIME );$etime = explode ( ' ', microtime () );return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );}/**
* 产生随机字符串
*
* @param int $length 输出长度
* @param string $chars 可选的 ,默认为 0123456789
* @return string 字符串
*/
function random($length, $chars = '0123456789') {$hash = '';$max = strlen($chars) - 1;for($i = 0; $i < $length; $i++) {$hash .= $chars[mt_rand(0, $max)];}return $hash;}/**
* 将字符串转换为数组
*
* @paramstring$data字符串
* @returnarray返回数组格式,如果,data为空,则返回空数组
*/
function string2array($data) {if($data == '') return array();eval("\$array = $data;");return $array;}/**
* 将数组转换为字符串
*
* @paramarray$data数组
* @parambool$isformdata如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @returnstring返回字符串,如果,data为空,则返回空
*/
function array2string($data, $isformdata = 1) {if($data == '') return '';if($isformdata) $data = new_stripslashes($data);return addslashes(var_export($data, TRUE));}/**
* 转换字节数为其他单位
*
*
* @paramstring$filesize字节大小
* @returnstring返回大小
*/
function sizecount($filesize) {if ($filesize >= 1073741824) {$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';} elseif ($filesize >= 1048576) {$filesize = round($filesize / 1048576 * 100) / 100 .' MB';} elseif($filesize >= 1024) {$filesize = round($filesize / 1024 * 100) / 100 . ' KB';} else {$filesize = $filesize.' Bytes';}return $filesize;}/**
* 查询字符是否存在于某字符串
*
* @param $haystack 字符串
* @param $needle 要查找的字符
* @return bool
*/
function str_exists($haystack, $needle){return !(strpos($haystack, $needle) === FALSE);}/**
* 取得文件扩展
*
* @param $filename 文件名
* @return 扩展名
*/
function fileext($filename) {return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));}/**
* 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
* @param $data 条件数组或者字符串
* @param $front 连接符
* @param $in_column 字段名称
* @return string
*/
function to_sqls($data, $front = ' AND ', $in_column = false) {if($in_column && is_array($data)) {$ids = '\''.implode('\',\'', $data).'\'';$sql = "$in_column IN ($ids)";return $sql;}else{if ($front == '') {$front = ' AND ';}if(is_array($data) && count($data) > 0) {$sql = '';foreach ($data as $key => $val) {$sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";}return $sql;}else{return $data;}}}/**
* 判断email格式是否正确
* @param $email
*/
function is_email($email) {return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);}/**
* 文件下载
* @param $filepath 文件路径
* @param $filename 文件名称
*/
function file_down($filepath, $filename = '') {if(!$filename) $filename = basename($filepath);if(is_ie()) $filename = rawurlencode($filename);$filetype = fileext($filename);$filesize = sprintf("%u", filesize($filepath));if(ob_get_length() !== false) @ob_end_clean();header('Pragma: public');header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');header('Cache-Control: no-store, no-cache, must-revalidate');header('Cache-Control: pre-check=0, post-check=0, max-age=0');header('Content-Transfer-Encoding: binary');header('Content-Encoding: none');header('Content-type: '.$filetype);header('Content-Disposition: attachment; filename="'.$filename.'"');header('Content-length: '.$filesize);readfile($filepath);exit;}/**
* 判断字符串是否为utf8编码,英文和半角字符返回ture
* @param $string
* @return bool
*/
function is_utf8($string) {return preg_match('%^(?:[\x09\x0A\x0D\x20-\x7E] # ASCII| [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte| \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs| [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte| \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates| \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3| [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15| \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16)*$%xs', $string);}/**
* 对用户的密码进行加密
* @param $password
* @param $encrypt //传入加密串,在修改密码时做认证
* @return array/password
*/
function password($password, $encrypt='') {$pwd = array();$pwd['encrypt'] = $encrypt ? $encrypt : create_randomstr();$pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);return $encrypt ? $pwd['password'] : $pwd;}/**
* 生成随机字符串
* @param string $lenth 长度
* @return string 字符串
*/
function create_randomstr($lenth = 6) {return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');}/**
* 检查密码长度是否符合规定
*
* @param STRING $password
* @return TRUE or FALSE
*/
function is_password($password) {$strlen = strlen($password);if($strlen >= 6 && $strlen <= 20) return true;return false;}/**
* 检测输入中是否含有错误字符
*
* @param char $string 要检查的字符串名称
* @return TRUE or FALSE
*/
function is_badword($string) {$badwords = array("\\",'&',' ',"'",'"','/','*',',','<','>',"\r","\t","\n","#");foreach($badwords as $value){if(strpos($string, $value) !== FALSE) {return TRUE;}}return FALSE;}/**
* 检查用户名是否符合规定
*
* @param STRING $username 要检查的用户名
* @return TRUE or FALSE
*/
function is_username($username) {$strlen = strlen($username);if(is_badword($username) || !preg_match("/^[a-zA-Z0-9_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]+$/", $username)){return false;} elseif ( 20 <= $strlen || $strlen < 2 ) {return false;}return true;}/**
* 检查id是否存在于数组中
*
* @param $id
* @param $ids
* @param $s
*/
function check_in($id, $ids = '', $s = ',') {if(!$ids) return false;$ids = explode($s, $ids);return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);}/**
* 对数据进行编码转换
* @param array/string $data 数组
* @param string $input 需要转换的编码
* @param string $output 转换后的编码
*/
function array_iconv($data, $input = 'gbk', $output = 'utf-8') {$encode_arr = array('UTF-8','ASCII','GBK','GB2312','BIG5','JIS','eucjp-win','sjis-win','EUC-JP');$encoded = mb_detect_encoding($data, $encode_arr);if (!is_array($data)) {return mb_convert_encoding($data, $output, $encoded);}else {foreach ($data as $key=>$val) {if(is_array($val)) {$data[$key] = array_iconv($val, $input, $output);} else {$data[$key] = mb_convert_encoding($data, $output, $encoded);}}return $data;}}/**
* 函数:get_magic_quotes_gpc在OFF状态下处理字符串的函数.
* @param string $arr 需要处理的字符串
*/
function strip_magic_quotes($arr){ foreach ($arr as $k => $v) { if (is_array($v)) { $arr[$k] = strip_magic_quotes($v); } else { $arr[$k] = stripslashes($v); } } return $arr;}if (get_magic_quotes_gpc()){ if (!empty($_GET)) { $_GET = strip_magic_quotes($_GET); } if (!empty($_POST)) { $_POST = strip_magic_quotes($_POST); } if (!empty($_COOKIE)) { $_COOKIE = strip_magic_quotes($_COOKIE); }}/**
* 表单验证的函数
* @param $form_vars 数组
*/
function filled_out($form_vars){ // test that each variable has a value foreach ($form_vars as $key => $value) { if (!isset($key) || ($value == '')) return false; } return true;}/**
* js中的escape及unescape函数的php实现
* 在用js传递数据的时候经常会用到的!
*/
function phpescape($str){ $sublen=strlen($str); $retrunString=""; for ($i=0;$i<$sublen;$i++) { if(ord($str[$i])>=127) { $tmpString=bin2hex(iconv("gb2312","ucs-2",substr($str,$i,2))); //$tmpString=substr($tmpString,2,2).substr($tmpString,0,2);window下可能要打开此项 $retrunString.="%u".$tmpString; $i++; } else { $retrunString.="%".dechex(ord($str[$i])); } } return $retrunString;}function unescape($str) { $str = rawurldecode($str); preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U",$str,$r); $ar = $r[0]; foreach($ar as $k=>$v) { if(substr($v,0,2) == "%u") $ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,-4))); elseif(substr($v,0,3) == "&#x") $ar[$k] = iconv("UCS-2","GBK",pack("H4",substr($v,3,-1))); elseif(substr($v,0,2) == "&#") { $ar[$k] = iconv("UCS-2","GBK",pack("n",substr($v,2,-1))); } } return join("",$ar);}/*
* 返回最佳图片的高度,宽度。以及原来的高度和宽度
* @param $ImgFile 图片地址
* @param $ImgW 需要处理的图片宽度
* @param $ImgH 需要处理的图片高度
* @param $SrcH 原高度
* @param $SrcW 原宽度
* @param $DstH 目标高度
* @param $DstW 目标宽度
* 调用时用 list($SrcW,$SrcH,$DstW,$DstH) = RtImageSize($ImgFile,200,200)
*/
function RtImageSize($ImgFile,$ImgW,$ImgH){ if(file_exists($ImgFile)) { $Size = @GetImageSize($ImgFile); $SrcW = $Size[0]; $SrcH = $Size[1]; $Ratio = max($SrcW/$ImgW,$SrcH/$ImgH); $DstW = ($SrcW / $Ratio); $DstH = ($SrcH / $Ratio); } return array($SrcW,$SrcH,$DstW,$DstH);}/*
* 防止表单被重复提交的函数
* 注意:用submit_table()函数之前不能有任何输出
*
* @param string $get_name 提交(submit)过来的变量名称
* @param string $var_name 用来存储$get_name内容的变量名
* @return boolean
*
* 用例:
* if(submit_table('t1'))echo $t1;
* else echo " 已提交过!";
*
*/
function submit_table($get_name,$var_name="SUBMIT_TABLE"){ if(!isset($_SESSION[$var_name])){ $_SESSION[$var_name] =false; } @session_start(); if(session_is_registered($var_name)){ ; }else{ session_register($var_name); } if (isset($get_name) and $_SESSION[$var_name]<>$get_name) { $_SESSION[$var_name] = $get_name; return true; } else { return false; }}/*
* 插入规定大小范围的图片
* @param string $imagePath 图片路径
* @param int $w 图片的宽
* @param int $h 图片的高
* @return string 图片标签
*/
function imgWH($imagePath,$w=120,$h=100){ $agesize = getimagesize($imagePath); $num=array(); if($agesize[0]>$agesize[1]){ $num['H']=intval($agesize[1]/$agesize[0]*$w); $num['W']=$w; }else{ $num['H']=$h; $num['W']=intval($agesize[0]/$agesize[1]*$h); } $img="<img src='{$imagePath}' title='{$num['W']}x{$num['H']}' width='{$num['W']}' height='{$num['H']}' border='0' />"; return $img;}/*
*把全角数字转为半角数字
* @param string $fnum 转换的数字串
*/
function GetAlabNum($fnum){$nums = array("0","1","2","3","4","5","6","7","8","9");$fnums = "0123456789";for($i=0;$i<=9;$i++) $fnum = str_replace($nums[$i],$fnums[$i],$fnum);$fnum = ereg_replace("[^0-9.]|^0{1,}","",$fnum);if($fnum=="") $fnum=0;return $fnum; }/*
* 去除HTML标记
* @param string $txt 需要处理的代码
*/
function Text2Html($txt){$txt = str_replace(" "," ",$txt);$txt = str_replace("<","<",$txt);$txt = str_replace(">",">",$txt);$txt = preg_replace("/[rn]{1,}/isU","rn",$txt);return $txt; }/*
* 读取文件函数
* @param string $file_name 文件名字
*/
function readfromfile($file_name) {if (file_exists($file_name)) {$filenum=fopen($file_name,"r");flock($filenum,LOCK_EX);$file_data=fread($filenum, filesize($file_name));rewind($filenum);fclose($filenum);return $file_data;}}/**
* 写文件
* @param $file 文件名字
* @param $cont 内容
* @param $mod 模式
*/
function write_file($file, $cont, $mod = 'wb') {$oldmask = umask(0);if (!($fp=@fopen($file, $mod))) {@fclose($fp);return false;}flock($fp, LOCK_EX);@fwrite($fp, $cont);flock($fp, LOCK_UN);fclose($fp);umask($oldmask);}/**
* 301 重定向
* 用于非目录向目录重定向
* @param $url 重定向网址
* @param $time 重定时间
*/
function header301($url){header( "HTTP/1.1 301 Moved Permanently" );header( "Location: $url" );exit;}/**
* 定时跳转重定向
* 用于非目录向目录重定向
* @param $url 重定向网址
* @param $time 重定时间
*/
function jump($url,$time){header("refresh:$time;url=$url");echo "<meta http-equiv='Refresh' content=$time;URL=$url>";echo "<div align='center'>请稍等...该页将在".$time."秒后自动跳转!</div><br>";echo "<div align='center'><a href='$url'>如不能自动跳转,请点击这里</div>";}/**
* AJAX廷时重定向
* @param $url 跳转URL
* @param $time 廷时秒数
* @param $space
* */
function jsRedirect($url,$time=3,$message=null,$space=null){$hash = create_randomstr();$fn = 'fn'.$hash;$message = $message?$message:'操作成功!';$str = "<div align='center'><div style='padding:10px 20px;'>$message</div>该页将在 <span id='".$hash."'>$time</span>秒后自动跳转!</div>";$str .= '<script language=javascript>var int=self.setInterval("'.$fn.'()",1000);function '.$fn.'(){var t=document.getElementById("'.$hash.'").innerHTML-1;document.getElementById("'.$hash.'").innerHTML=t;}</script>';if($space!=null){$str .= "<script type='text/javascript'>window.setTimeout('$(\'#$space\').load(\'$url\')',$time*1000)</script>";}else{$str .= "<meta http-equiv='Refresh' content=$time;URL=$url>";}echo $str;}/**
* 主要是用来替换关键词 如:关键字加粗加红
* @param $isreplace 查找的值 数组
* @param $replace 替换 $isreplace 中的值的值 数组
* @param $str 要处理的字符串
*/
function strong($isreplace=array(),$replace=array(),$str){$str = strip_tags($str);return str_replace($isreplace,$replace,$str);}/**
* 清除数据两边的多余空格
*
* @param $data 要进行处理的数据
*/
function trims($data) {if(is_array($data)) {return array_map("trims", $data);}else {return trim($data);}}//过滤所有空格,回车,换行
function loseSpace($data){$data = preg_replace("/ /","",$data);$data = preg_replace("/ /","",$data);$data = preg_replace("/ /","",$data);$data = preg_replace("/\r\n/","",$data);$data = str_replace(chr(13),"",$data);$data = str_replace(chr(10),"",$data);$data = str_replace(chr(9),"",$data);return $data;}/**
* 过滤掉链接中所有非本站的网址链接
* @param $str 要进行过滤的HTML内容
*_DOMAIN_NAME_ 请自行定义
*/
function FilterLinks($str) {preg_match_all('/\<a[^\>]*\>(.*?)\<\/a\>/i', $str, $links); $DOMAIN_NAME = 'c.com';foreach($links[0] as $index=>$item) {preg_match_all('/href=\"(.*?)\"/i', $item, $sub);if(!preg_match('/http:\/\/(\w+?)(\.cn){0,1}\.'.$DOMAIN_NAME.'/i', $sub[1][0]) && preg_match('/^http:\/\/.*?/i', $sub[1][0])) {$str = str_replace($item, $links[1][$index], $str);}}return $str;}/**
* 计算百分比
* @param $total 总数
* @param $num 基数
* @param $len 小数点长度
*/
function percent($total, $num, $len=2) {if($total == 0) {return 0;}else {return round(($num/$total)*100, $len);}}/**
* 通过邮箱地址,返回邮箱的登陆网址
* @param $email 邮箱地址
*/
function getPostOffice($email) {// $post = Cache::getCache("postoffice");// $keys = array_keys($post);$domain = substr(strstr($email, "@"),1);// if (in_array($domain, $keys)) {// return $post[$domain];// }// else {return "http://mail.".$domain;// }}/**
* 验证码
* @param int $num 字符个数
* @param int $size 字符大小
* @param int $width 验证码宽度
* @param int $height 决验证码高度
* @放一个font.ttf 字体到目录下
* @调用方法:vCode(4,20,100,50);
*/
function vCode($num=4,$size=20, $width=0,$height=0){ !$width && $width = $num*$size*4/5+5; !$height && $height = $size + 10; // 去掉了 0 1 O l 等 $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVW"; $code = ''; for ($i=0; $i<$num; $i++){ $code.= $str[mt_rand(0, strlen($str)-1)]; } // 画图像 $im = imagecreatetruecolor($width,$height); // 定义要用到的颜色 $back_color = imagecolorallocate($im, 235, 236, 237); $boer_color = imagecolorallocate($im, 118, 151, 199); $text_color = imagecolorallocate($im, mt_rand(0,200), mt_rand(0,120), mt_rand(0,120)); // 画背景 imagefilledrectangle($im,0,0,$width,$height,$back_color); // 画边框 imagerectangle($im,0,0,$width-1,$height-1,$boer_color); // 画干扰线 for($i=0;$i<5;$i++){ $font_color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); imagearc($im,mt_rand(-$width,$width),mt_rand(-$height,$height),mt_rand(30,$width*2),mt_rand(20,$height*2),mt_rand(0,360),mt_rand(0,360),$font_color); } // 画干扰点 for($i=0;$i<50;$i++){ $font_color = imagecolorallocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$font_color); } // 画验证码 imagefttext($im, $size , 0, 5, $size+3, $text_color, './font.ttf',$code); header("Cache-Control: max-age=1, s-maxage=1, no-cache, must-revalidate"); header("Content-type: image/png"); imagepng($im); imagedestroy($im); }/**
* 获取百度的热词
* @return array 返回百度的热词数据(数组返回)
*/
function getBaiduHotKeyWord(){$templateRss = file_get_contents('http://top.baidu.com/rss_xml.php?p=top10');If (preg_match('/<table>(.*)<\/table>/is', $templateRss, $_description)) {$templateRss = $_description [0];$templateRss = str_replace("&", "&", $templateRss);}$templateRss = "<?xml version=\"1.0\" encoding=\"GBK\"?>" . $templateRss;$xml = simplexml_load_String($templateRss);foreach ($xml->tbody->tr as $temp) {if (!empty ($temp->td->a)) {$keyArray [] = trim(($temp->td->a));}}return $keyArray;}/**
*
* getOptions 参数列表:
* - result Options 数组
* - vals Options 数组修改的键值 (Value)
* - except Options 除"except"值外的数据调用
* - same Value和Title 值是否相同
* - exceptKey Options 除"exceptKey"键外的数据调用
*
* @return Array() $options
*/
function getOptions($result,$vals='whatthehellisthis',$except='',$same='',$exceptKey='') { if(!$result) return false; $options = ""; while(list($key,$val) = each($result)) { $checkVal = false; if($except) { if(is_array($except)) $checkVal = in_array($val,$except); else { if($except == $val) $checkVal = true; } } if($exceptKey) { if(is_array($exceptKey)) $checkVal = in_array($key,$exceptKey); else { if($exceptKey == $key) $checkVal = true; } } if(!$checkVal) { if($same) $key = $val; $options .= "<option value='".$key."'"; if($key == $vals) $options .= " selected"; $options .= ">".$val."</option>\n"; } } return $options;}/**
*
* getRadios 参数列表:
* - result Radio 数组
* - name Radio 名字
* - checked 默认选中第一个,通读索引控制 Radio 的 Checked 状态
* - vals 通过VALUE控制 Radio 的 Checked 状态
* - except Radios 除"except"值外的数据调用
* - enter 换行参数
* - Events 事件参数
* - style 样式参数
* - disabled 显示参数
* - exceptKey Radios 除"exceptKey"键外的数据调用
*
* @return Array() $radios
*/
function getRadios($result ,$name="radio" ,$checked='0' ,$vals='whatthehellisthis' ,$except='' ,$enter='0', $Events='' ,$style='border:solid 1 #FFFFFF;' ,$disabled='' ,$exceptKey='') { if(!$result) return false; $radios = ''; $i = 0; foreach ($result as $key => $val) { $checkVal = false; if($except) { if(is_array($except)) $checkVal = in_array($val,$except); else { if($except == $val) $checkVal = true; } } if($exceptKey) { if(is_array($exceptKey)) $checkVal = in_array($key,$exceptKey); else { if($exceptKey == $key) $checkVal = true; } } if(!$checkVal) { $radios .= "<input name='".$name."' type='radio' value='".$key."'"; if($key == $vals) $radios .= " checked"; if ($checked != 'no' && $checked == $i) { $radios .= " checked"; } if ($disabled != "" && $disabled[$i] == 1) { $radios .= " disabled"; } $radios .= " style='".$style."' ".$Events.">".$val." "; } $i++; if ($enter !=0 && ($i % $enter) ==0) { $radios .="<Br>"; } } return $radios;}/**
*
* getCheckboxs 参数列表:
* - result Checkbox 数组
* - name Checkbox 名字
* - checked 默认选中第一个,通读索引控制 Checkbox 的 Checked 状态
* - vals 通过VALUE控制 Checkbox 的 Checked 状态
* - except Checkboxs 除"except"值外的数据调用
* - enter 换行参数
* - Events 事件参数
* - style 样式参数
* - disabled 显示参数
* - exceptKey Checkboxs 除"exceptKey"键外的数据调用
*
* @return Array() $Checkboxs
*/
function getCheckboxs($result,$name='Checkboxs', $checked='0', $vals='whatthehellisthis',$except='',$enter='0',$Events='',$style='' ,$disabled='',$exceptKey='') { if(!$result) return false; $Checkboxs = ""; $i = 0; foreach ($result as $key => $val) { $checkVal = false; if($except) { if(is_array($except)) $checkVal = in_array($val,$except); else { if($except == $val) $checkVal = true; } } if($exceptKey) { if(is_array($exceptKey)) $checkVal = in_array($key,$exceptKey); else { if($exceptKey == $key) $checkVal = true; } } if(!$checkVal) { $Checkboxs .= "<input name='".$name."' type='Checkbox' value='".$key."'"; if(is_array($vals) && array_key_exists($key,$vals)) $Checkboxs .= " checked"; if(!is_array($vals) && $key == $vals) $Checkboxs .= " checked"; if ($checked != 'no' && $checked == $i) { $Checkboxs .= " checked"; } if ($disabled<>"" && $disabled[$i] ==1) { $Checkboxs .= " disabled"; } $Checkboxs .= " style=".$style." ".$Events.">".$val." "; } $i++; if ($enter !=0 && ($i % $enter) ==0) { $Checkboxs .="<Br>"; } } return $Checkboxs;}/**
* 数组重建索引
* */
function updateKeyForArray($array){$i=0;foreach($array as $arr){$newarr[$i]=$arr;$i++;}return $newarr;}/**
* 简化findall数据
* */
function simplifyData($data){foreach($data as $key=>$val){$newData[$key] = $val->attributes;}return $newData;}/**
* 获取会员存储在cookie里面的ID
* */
function getUserId(){$cookie = Yii::app()->request->getCookies();if($cookie['MemberID'] != null){$zm_id = $cookie['MemberID']->value;}else{$zm_id = NULL;}return $zm_id;}/**
* This is the shortcut to Yii::app()
*/
function app(){return Yii::app();}/**
* This is the shortcut to Yii::app()->clientScript
*/
function cs(){// You could also call the client script instance via Yii::app()->clientScript// But this is fasterreturn Yii::app()->getClientScript();}/**
* 加载JS
*/
function regjs($name){// You could also call the client script instance via Yii::app()->clientScript// But this is fasterreturn Yii::app()->clientScript->registerCoreScript($name);}/**
* 加载JS
*/
function jsfile($file){ return Yii::app()->clientScript->registerScriptFile($file);}/**
* 加载CSS
*/
function cssfile($file){ return Yii::app()->clientScript->registerCssFile($file);}/**
* This is the shortcut to Yii::app()->user.
*/
function user(){return Yii::app()->getUser();}/**
* This is the shortcut to Yii::app()->createUrl()
*/
function url($route,$params=array(),$ampersand='&'){return Yii::app()->createUrl($route,$params,$ampersand);}/**
* 创建绝对地址
* This is the shortcut to Yii::app()->createAbsoluteUrl()
*/
function domainurl($route,$params=array(),$schema='',$ampersand='&'){return Yii::app()->createAbsoluteUrl($route,$params,$schema,$ampersand);}/**
* This is the shortcut to CHtml::encode
*/
function h($text){return htmlspecialchars($text,ENT_QUOTES,Yii::app()->charset);}/**
* This is the shortcut to CHtml::link()
*/
function l($text, $url = '#', $htmlOptions = array()){return CHtml::link($text, $url, $htmlOptions);}/**
* This is the shortcut to Yii::t() with default category = 'stay'
*/
function t($message, $category = 'msg', $params = array(), $source = null, $language = null){return Yii::t($category, $message, $params, $source, $language);}/**
* This is the shortcut to Yii::app()->request->baseUrl
* If the parameter is given, it will be returned and prefixed with the app baseUrl.
*/
function bu($url=null){static $baseUrl;if ($baseUrl===null)$baseUrl=Yii::app()->getRequest()->getBaseUrl();return $url===null ? $baseUrl : $baseUrl.'/'.ltrim($url,'/');}/**
* Returns the named application parameter.
* This is the shortcut to Yii::app()->params[$name].
*/
function param($name){return Yii::app()->params[$name];}/**
* Dump as many variables as you want. Infinite parameters.
*/
function dump(){$args = func_get_args();foreach($args as $k => $arg){echo '<fieldset class="debug"> <legend>'.($k+1).'</legend>';CVarDumper::dump($arg, 10, true);echo '</fieldset>';}}function sess($key = null, $value = null){if (!empty ($key) && !empty ($value)){return Yii::app()->session[$key] = $value;}elseif (!empty ($key)){return Yii::app()->session[$key];}else{return Yii::app()->session;}}function getSessArr(){return sess()->toArray();}function getSessId(){return sess()->sessionID;}//重新生成SESSIONSID
function regenSessId(){return sess()->regenerateId();}function printSess(){echo '<pre>';foreach (getSessArr() as $key => $value){echo ' '.$key .' -> '.$value.'<br/>';}echo '</pre>';}function removeSess($key){return sess()->remove($key);}function destroySess(){return sess()->destroy();}/**
* @return string the generated image tag
*/
function i($src, $alt='', $htmlOptions=array()) {return CHtml::image($src, $alt, $htmlOptions);}/**
* 信息提示
* @param string $message 提示内容
* @param int $type 类型
* @param string $status 状态:success 成功,error 错误
* @param array $link
* @return array
*/
function Message($message,$type ='404') {throw new CHttpException($type,$message); exit; }/* set a flash message to display after the request is done */
function setFlash($message,$id='mysite') { Yii::app()->user->setFlash($id, $message); } function hasFlash($id='mysite') { return Yii::app()->user->hasFlash($id); } /* retrieve the flash message again */ function getFlash($id='mysite') { if (Yii::app()->user->hasFlash($id)) { return Yii::app()->user->getFlash($id); } } function getErrorFlash($id='mysite') { if (Yii::app()->user->hasFlash($id)) { echo '<p class="tip">'; echo getFlash($id); echo '</p>'; Yii::app()->clientScript->registerScript('fade', "setTimeout(function() { $('.tip').fadeOut('slow'); }, 5000);"); } }function renderFlash($id='mysite') { if (Yii::app()->user->hasFlash($id)) { echo '<div class="errorSummary">'; echo getFlash($id); echo '</div>'; Yii::app()->clientScript->registerScript('fade', "setTimeout(function() { $('.errorSummary').fadeOut('slow'); }, 5000);"); }}//弹出框提示
function getAlertFlash($id='mysite') {if (Yii::app()->user->hasFlash($id)) {Yii::app()->clientScript->registerScript('fade', 'alert_tips("","'.getFlash($id).'");');}}/**
* 将XML转为ARRAY
* @param string $data XML数据
* @return array
*/
function xml2array($data){return $array = json_decode(json_encode(simplexml_load_string($data)),TRUE);}/**
* 将ARRAY转为XML
* @param array $arr ARRAY数据
* @param int $dom ARRAY数据
* @param int $item ARRAY数据
* @param string/array $element ARRAY数据
* @return array
*/
function arraytoxml($arr,$dom=0,$item=0,$element='Orders'){ if (!$dom){ $dom = new DOMDocument("1.0","utf-8"); $dom->formatOutput = true; } if(!$item){ if(is_array($element)){ $item = $dom->createElement($element[0]); }else{ $item = $dom->createElement($element); } $dom->appendChild($item); } foreach ($arr as $key=>$val){ if(is_array($element)){ $itemx = $dom->createElement(is_string($key)?$key:$element[1]); }else{ $itemx = $dom->createElement(is_string($key)?$key:"item"); } $item->appendChild($itemx); if (!is_array($val)){ $text = $dom->createTextNode($val); $itemx->appendChild($text); }else { arraytoxml($val,$dom,$itemx); } } return $dom->saveXML();}/**
* 将json转为XML
* @param string $source json数据
* @param string $charset 编码
* @return array
*/
function json_to_xml($source,$charset='utf8') { if(emptyempty($source)){ return false; } $array = json_decode($source); //php5,以及以上,如果是更早版本,請下載JSON.php $xml ='<!--l version="1.0" encoding="'.$charset.'-->'; $xml .= $this->change($array); return $xml; } function change($source) { $string="";foreach($source as $k=>$v){$string .="<".$k.">";if(is_array($v) || is_object($v)){ //判断是否是数组,或者,对像$string .= $this->change($v); //是数组或者对像就的递归调用}else{$string .=$v; //取得标签数据}$string .=""; }return $string; }/**
* 生成指定的客服链接
* @param string $id 号码
* @param int $type 客服类型:1:qq,2:MSN 3旺旺
* @return string
*/
function kefu($id,$type=1){if( $type == 1 ){$link = '<a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin='.$id.'&site=qq&menu=yes"><img border="0" src="'.Yii::app()->HomeUrl.'/images/qqonline.png" alt="点击这里给我发消息" title="点击这里给我发消息"/></a>';}elseif( $type == 2 ){$link = '<a target="blank" href="msnim:chat?contact='.$id.'">MSN在线客服</a>';}else{$link = '<a target="_blank" href="http://amos.im.alisoft.com/msg.aw?v=2&uid='.$id.'&site=cnalichn&s=1&charset=utf-8" ><img border="0" src="http://amos.im.alisoft.com/online.aw?v=2&uid='.$id.'&site=cnalichn&s=1&charset=utf-8" alt="点此咨询"" /></a>';}return $link;}/**
* 把数组加密为URL可传递的字符串,只支持一维数组
* @param array $params
* @return string
*/
function encryptParamsForUrl($params){if(is_array($params)){$keys = array_keys($params);$values = array_values($params);$keystr = implode('}^{',$keys);$valuestr = implode('}^{',$values);$hashstr = $keystr.'{)^.^(}'.$valuestr;$hash = Yii::app()->securityManager->encrypt($hashstr);return urlencode($hash);}}/**
* 把URL加密串解密,返回数组
* @param string $hash
* @return array
*/
function decryptParamsForUrl($hash){if(is_string($hash)){$hash = Yii::app()->securityManager->decrypt(urldecode($hash));$arrays = explode('{)^.^(}',$hash);$keyarray = explode('}^{',$arrays[0]);$valuearray = explode('}^{',$arrays[1]);$array = array();foreach ($keyarray as $key=>$value){$array[$value] = $valuearray[$key];}return $array;}}/**
* 得到新订单号
* @return string
*/
function get_order_id() { /* 选择一个随机的方案 */ mt_srand((double) microtime() * 1000000); return date('Ymd') . str_pad(mt_rand(1, 999999), 6, '0', STR_PAD_LEFT);}/**
* 货币格式化
*/
function money($int){return number_format($int, 2, '.', '');}
?>
- php、yii通用globals方法
- php安装yii-advanced方法
- php $GLOBALS 详解
- php全局变量漏洞 $GLOBALS
- php post数据通用方法
- php变量范围 $GLOBALS global
- php://input &$GLOBALS["HTTP_RAW_POST_DATA"]&$_POST
- $GLOBALS
- GLOBALS
- GLOBALS
- php 解决乱码的通用方法
- PHP扩展编译通用的方法
- linux下 php扩展的通用方法
- PHP中$GLOBALS['HTTP_RAW_POST_DATA'] 和 $_POST
- 关于 PHP 的 global 和 $GLOBALS
- PHP中global与$GLOBALS['']区别
- 关于php中的超全局变量$GLOBALS
- PHP中global与$GLOBALS['']区别
- FFT(快速傅立叶算法 for java)
- 中移动净利下滑 玩不转互联网是主因
- JavaSwing实现树形结构
- Spring不配置视图解析器问题
- 获取系统信息
- php、yii通用globals方法
- LeetCode Permutations I && II
- Jsp中的Application使用
- unity3d 阴影效果图——在制作过程中的注意事项
- CSS的width:100%和width:auto区别
- session-request-page-application的作用域
- sp_who, sp_who2和sp_who3
- [转]错误“AxImp.exe”已退出,代码为 -1163019603。
- How Linkers Use Static Libraries to Resolve References