www.0g.com/source/common.php
2021-08-30 15:33:51 +08:00

1220 lines
36 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* 添加转义符号
* @param mix $string
* @return mix $string
*/
function saddslashes($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = saddslashes($val);
}
} else {
$string = addslashes($string);
}
return $string;
}
/**
*在52服务器上执行mongodb搜索语句
* @param type $db
* @param type $coll
* @return type
*/
function getCollection_52($db,$coll)
{
$conn=getMongo_52();
$db=$conn->selectDB($db);
$collection=$db->selectCollection($coll);
return $collection;
}
/**
* 链接52mongodb
* @return \MongoClient
*/
function getMongo_52()
{
try {
$conn=new MongoClient("192.168.1.52:52017");
} catch (Exception $e) {
echo 'connect mongo error:52';exit;
}
return $conn;
}
/**
* 取消HTML代码
* @param type $string
* @return type
*/
function shtmlspecialchars($string) {
if(is_array($string)) {
foreach($string as $key => $val) {
$string[$key] = shtmlspecialchars($val);
}
} else {
$string = 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;'), $string));
}
return $string;
}
/**
* 字符串加密解密
* @param string $string
* @param string $operation ENCODE:加密|DECODE:解密
* @param type $key
* @param type $expiry
* @return string
*/
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 0; // 随机密钥长度 取值 0-32;
// 加入随机密钥,可以令密文无任何规律,即便是原文和密钥完全相同,加密结果也会每次不同,增大破解难度。
// 取值越大,密文变动规律越大,密文变化 = 16 的 $ckey_length 次方
// 当此值为 0 时,则不产生随机密钥
$key = md5($key ? $key : UC_KEY);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya.md5($keya.$keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
for($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if($operation == 'DECODE') {
if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc.str_replace('=', '', base64_encode($result));
}
}
/**
* 检查邮箱是否有效
* @param type $email
* @return type
*/
function isemail($email) {
return strlen($email) > 6 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
}
/**
* 过滤关键字符
* @param type $str
* @return type
*/
function inputFilter($str)
{
if(empty($str))
{
return;
}
if($str=="")
{
return $str;
}
$str=trim($str);
$str=str_replace("&","&amp;",$str);
$str=str_replace(">","&gt;",$str);
$str=str_replace("<","&lt;",$str);
$str=str_replace(chr(34),"&",$str);
$str=str_replace(chr(39),"&#39;",$str);
$str=str_replace(chr(13),"<br />",$str);
$str=str_replace("'","''",$str);
$str=str_replace("select","sel&#101;ct",$str);
$str=str_replace("join","jo&#105;n",$str);
$str=str_replace("union","un&#105;on",$str);
$str=str_replace("where","wh&#101;re",$str);
$str=str_replace("insert","ins&#101;rt",$str);
$str=str_replace("delete","del&#101;te",$str);
$str=str_replace("update","up&#100;ate",$str);
$str=str_replace("like","lik&#101;",$str);
$str=str_replace("drop","dro&#112;",$str);
$str=str_replace("create","cr&#101;ate",$str);
$str=str_replace("modify","mod&#105;fy",$str);
$str=str_replace("rename","ren&#097;me",$str);
$str=str_replace("alter","alt&#101;r",$str);
$str=str_replace("cast","ca&#115;",$str);
return $str;
}
/**
* 截取字符串,中英文
* @param type $str
* @param type $start
* @param type $len
* @return type
*/
function msubstr($str, $start, $len) {
$tmpstr = "";
$strlen = $start + $len;
for($i = 0; $i < $strlen; $i++) {
if(ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}
/**
* 获取IP
* @return type
*/
function getip(){
//判断服务器是否允许$_SERVER
if(isset($_SERVER)){
if(isset($_SERVER[HTTP_X_FORWARDED_FOR])){
$realip = $_SERVER[HTTP_X_FORWARDED_FOR];
}elseif(isset($_SERVER[HTTP_CLIENT_IP])) {
$realip = $_SERVER[HTTP_CLIENT_IP];
}else{
$realip = $_SERVER[REMOTE_ADDR];
}
}else{
//不允许就使用getenv获取
if(getenv("HTTP_X_FORWARDED_FOR")){
$realip = getenv( "HTTP_X_FORWARDED_FOR");
}elseif(getenv("HTTP_CLIENT_IP")) {
$realip = getenv("HTTP_CLIENT_IP");
}else{
$realip = getenv("REMOTE_ADDR");
}
}
$realip=trim($realip,',');
$arr_ip=explode(',',$realip);
return $arr_ip[count($arr_ip)-1];
}
/**
* 创建目录
* @param type $typedir 要创建的目录
*/
function createDir($typedir)
{
if(!is_dir($typedir))
{
mkdir($typedir,0744,true);
}
}
// 单例模式的数据库操作函数 - qiangwan_hwzs
function getinstance2() {
require_once S_ROOT . 'source/libs/Db2.class.php';
return Dbhelper1::getinstance();
}
function getonerecord2($query) {
global $tp;
$db = getinstance2();
$db->localPath=$tp;
return $db->getonerecord($query);
}
function getrecord_array($query){
global $tp;
$db = getinstance2();
$data=array();
$db->localPath=$tp;
$resource=$db->exec_db($query);
if($resource){
while($row= mysqli_fetch_array($resource,MYSQLI_ASSOC)){
$data[]=$row;
}
}
return $data;
}
function exec_db_insertid2($query) {
global $tp;
$db = getinstance2();
$db->localPath=$tp;
return $db->exec_db_insertid($query);
}
function exec_db2($query) {
global $tp;
$db = getinstance2();
$db->localPath=$tp;
return $db->exec_db($query);
}
/**
* 获取单条记录
* @param type $query_str
* @return type
*/
// function getonerecord($query_str)
// {
// $result=exec_db($query_str);
// $row=mysql_fetch_array($result,MYSQL_ASSOC);
// return $row;
// }
//连接数据库
// function exec_db($query_str)
// {
// global $tp;
// $dblink=mysql_connect(DBHOST,DBUSER,DBPW,1,131072);
// if(!$dblink)
// {
// @dolog('mysql链接错误记录','域名:'.$_SERVER['SERVER_NAME']."\n".$tp."\n".$query_str);
// die("Query failed:");
// }
// mysql_select_db(DBNAME);
// mysql_query("SET NAMES 'utf-8'");
//
// $result=mysql_query($query_str) or die("Query failed:".dolog('sql语句错误','域名:'.$_SERVER['SERVER_NAME']."\n".$tp."\n".$query_str));
// mysql_close($dblink);
// return $result;
// }
//返回插入的ID
// function exec_db_insertid($query_str)
// {
// global $tp;
// $dblink=mysql_connect(DBHOST,DBUSER,DBPW,1,131072);
// mysql_select_db(DBNAME);
// mysql_set_charset('utf8',$dblink);
// $result=mysql_query($query_str) or die("Query failed:".mysql_error());
// $insertid = mysql_insert_id();
// mysql_close($dblink);
// return $insertid;
// }
/**
* 获取链接数据库的 resource资源
* @return type
*/
// function getdblink()
// {
// $dblink=mysql_connect(DBHOST,DBUSER,DBPW,1,131072) or die("Connect to db failed");
// mysql_select_db(DBNAME,$dblink);
// mysql_query("SET NAMES 'utf8'",$dblink);
// return $dblink;
// }
// function exec_db_ps($query_str,$dblink)
// {
// $result=mysql_query($query_str,$dblink);
// if(!$result)
// {
// die("Query failed:".mysql_error());
// }
// return $result;
// }
/**
*
* @param string $query_str SQL 语句
* @param source $dblink 连接mysql资源
* @return array
*/
// function getrecord_array($query_str,$dblink){
// $dataArr=array();
// $result=exec_db_ps($query_str,$dblink);
// while($row= mysql_fetch_array($result,MYSQL_ASSOC)){
// $dataArr[]=$row;
// }
// return $dataArr;
// }
// function getonerecord_ps($query_str,$dblink)
// {
// $result=exec_db_ps($query_str,$dblink);
// $row=mysql_fetch_array($result,MYSQL_ASSOC);
// return $row;
// }
//本地的数据库插入最后的ID
// function get_insert_id($query_str)
// {
// global $tp;
// $dblink=mysql_connect(DBHOST,DBUSER,DBPW,1,131072) or die("Connect to db failed");
// mysql_select_db(DBNAME);
// mysql_query("SET NAMES 'utf8'");
// $result=mysql_query($query_str) or die("Query failed:". mysql_error().@dolog("connectMysqliError",$query_str."\n". mysql_errno()));
// $id=mysql_insert_id();
// mysql_close($dblink);
// return $id;
// }
//
function CheckEmail($email)
{
if (ereg("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+",$email))
{
return true;
}
else
{
return false;
}
}
function curl_file_get_contents($url,$is_ajax=false)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$r = curl_exec($ch);
curl_close($ch);
return $r;
}
function init_smarty()
{
include_once(S_ROOT."source/libs/Smarty.class.php");
$tpl = new Smarty();
$tpl->template_dir = S_ROOT."templates/";
$tpl->compile_dir = S_ROOT."templates_c/";
$tpl->cache_dir = S_ROOT."cache/";
$tpl->left_delimiter = '<!--{';
$tpl->right_delimiter = '}-->';
return $tpl;
}
function init_smarty_2()
{ global $appid;
include_once(S_ROOT."source/libs/Smarty.class.php");
$tpl = new Smarty();
$tpl->template_dir = S_ROOT."new_tpl/tpl5/";
$tpl->compile_dir = S_ROOT."new_tpl/tpl5_c/";
$tpl->cache_dir = S_ROOT."new_tpl/cache/";
$tpl->left_delimiter = '<!--{';
$tpl->right_delimiter = '}-->';
return $tpl;
}
function init_smarty_10()
{
include_once(S_ROOT."source/libs/Smarty.class.php");
$tpl = new Smarty();
$tpl->template_dir = S_ROOT."new_tpl/tpl10/";
$tpl->compile_dir = S_ROOT."new_tpl/tpl10_c/";
$tpl->cache_dir = S_ROOT."new_tpl/cache/";
$tpl->left_delimiter = '<!--{';
$tpl->right_delimiter = '}-->';
return $tpl;
}
/**
*
* @global type $tpl
* @param type $message
* @param type $url_forward
*/
function cpmessage($message,$url_forward='')
{
global $tpl;
if(!empty($url_forward))
{
$message .= "<script>setTimeout(\"window.location.href ='$url_forward';\",1000);</script>";
}else
{
$message .= "<script>setTimeout('window.history.go(-2);',1000);</script>";
}
echo $message;
exit;
}
function cpmessage2($message,$url_forward='')
{
if(!empty($url_forward))
{
$message .= "<script>setTimeout(\"window.location.href ='$url_forward';\",1000);</script>";
}else
{
$message .= "<script>setTimeout('window.history.go(-1);',1000);</script>";
}
echo $message;
exit;
}
/**
* 获取ip相应的地址
* @param type $ip
* @return string
*/
function getiparea($ip)
{
include_once(S_ROOT."source/ip/qqwry.php");
$QQWry=new QQWry;
$QQWry->QQWry($ip);
$area=trim($QQWry->Country);
if($area=="局域网")
{
$area="中国";
}
return $area;
}
/**
* 分页类
*/
function urlAnalyze($page) {
$url = $_SERVER['REQUEST_URI'];
$parse_url = parse_url($url);
$url_query = isset($parse_url['query']) ? $parse_url['query'] : '';
if (!empty($url_query)) {
if (strpos($url_query, 'page=') === false) {
$url .= '&page=PAGE';
} else {
$url = str_replace('page=' . trim($_GET['page']), 'page=PAGE', $url);
}
} else {
$url .= '?page=PAGE';
}
return $url;
}
/**
* 生成分页的HTML
* @param type $total
* @param type $page
* @param type $pagesize
* @return string
*/
function getPager($total, $page, $pagesize) {
$pageData = array();
$pageData['pageCount'] = ceil($total / $pagesize);
if ($page > $pageData['pageCount']) {
$page = $pageData['pageCount'];
}
if ($page - 1 > 0) {
$pageData['prevPage'] = $page - 1;
} else {
$pageData['prevPage'] = 1;
}
if ($pageData['pageCount'] >= $page + 1) {
$pageData['nextPage'] = $page + 1;
} else {
$pageData['nextPage'] = $pageData['pageCount'];
}
$pageData['lastPage'] = $pageData['pageCount'];
$nextPageUrl = urlAnalyze($page);
$html = '<div class="page_key" id="pagerInfo">';
$html .= '<a href="' . str_replace('PAGE', 1, $nextPageUrl) . '">首页</a>';
$html .= '<a class="forbidden" href="' . str_replace('PAGE', $pageData['prevPage'], $nextPageUrl) . '">上一页</a>';
//起始页码
$p_start = 1;
//终止页码
$p_end = 9;
if ($page >= 6) {
$p_end += ($page - 4) - 1;
}
if ($p_end > $pageData['pageCount']) {
$p_end = $pageData['pageCount'];
}
if ($p_end > 9) {
$p_start = $p_end - 9 + 1;
}
for ($i = $p_start; $i <= $p_end; $i++) {
if ($i == $page) {
$html .= '<a class="current" href="javascript:void(0)">' . $page . '</a>';
} elseif ($i > 0) {
$html .= '<a href="' . str_replace('PAGE', $i, $nextPageUrl) . '" >' . $i . '</a>';
}
}
$html .= '<a href="' . str_replace('PAGE', $pageData['nextPage'], $nextPageUrl) . '">下一页</a>';
$html .= '<a class="last" href="' . str_replace('PAGE', $pageData['lastPage'], $nextPageUrl) . '">末页</a>';
$html .= '<span>' . $total . '条/共' . $pageData['pageCount'] . '页</span>';
$html .= '</div>';
return $html;
}
function utftogbk($str)
{
$string = charset_encode ( "utf-8", "gb2312", $str);
return $string;
}
/**
*
*检测允许通过的ip
**/
function checkallowip($ALLOWED_IP)
{
$IP = getip();
$check_ip_arr = explode ( '.', $IP );
if (! in_array ( $IP, $ALLOWED_IP ))
{
foreach ( $ALLOWED_IP as $val )
{
if (strpos ( $val, '*' ) !== false){
$arr = array (); //
$arr = explode ( '.', $val );
$bl = true;
for($i = 0; $i < 4; $i ++)
{
if ($arr [$i] != '*')
{
if ($arr [$i] != $check_ip_arr [$i])
{
$bl = false;
break;
}
}
}
if ($bl){
return true;
}
}
}
return false;
} else{
return true;
}
}
/**
*
*gbk转utf编码
**/
function gbktoutf($string) {
$string = charset_encode ( "gb2312", "utf-8", $string );
return $string;
}
/**
* 字符转码
* @param type $_input_charset
* @param type $_output_charset
* @param type $input
* @return type
*/
function charset_encode($_input_charset, $_output_charset, $input) {
$output = "";
$string = $input;
if (is_array ( $input )) {
$key = array_keys ( $string );
$size = sizeof ( $key );
for($i = 0; $i < $size; $i ++) {
$string [$key [$i]] = charset_encode ( $_input_charset, $_output_charset, $string [$key [$i]] );
}
return $string;
} else {
if (! isset ( $_output_charset ))
$_output_charset = $_input_charset;
if ($_input_charset == $_output_charset || $input == null) {
$output = $input;
} elseif (function_exists ( "mb_convert_encoding" )) {
$output = mb_convert_encoding ( $input, $_output_charset, $_input_charset );
} elseif (function_exists ( "iconv" )) {
$output = iconv ( $_input_charset, $_output_charset, $input );
} else
die ( "sorry, you have no libs support for charset change." );
return $output;
}
}
function json_encode_k($array) {
return json_encode ( $array );
}
function echojson($msg = '', $status = 0, $dataarr = array()) {
if(!$dataarr)
{
$dataarr=array();
}
$arr = array (
'msg' => $msg,
'status' => $status.'',
'data' => $dataarr
);
echo json_encode_k ( $arr );die;
}
function echojson2($msg = '', $status = 0, $dataarr = array()) {
$msg = gbktoutf ( $msg );
$status = gbktoutf ( $status );
$dataarr = gbktoutf ( $dataarr );
if(!$dataarr)
{
$dataarr=array();
}
$arr = array (
'msg' => $msg,
'status' => $status.'',
'data' => $dataarr
);
return json_encode_k ( $arr );
}
/**
* xml转成array
* @param type $xml_str
* @return type
*/
function get_xml_toarr($xml_str)
{
$xml_o = simplexml_load_file($xml_str);
$xml_arr = objtoarray($xml_o);
return utftogbk($xml_arr);
}
/**
* 对象转成数组对象
* @param type $obj
* @return type
*/
function objtoarray($obj) {
if (is_object ( $obj )) {
$obj = ( array ) $obj;
}
if ($obj){
foreach ( $obj as $k => $o ) {
if (is_object ( $o ) || is_array ( $o )) {
$obj [$k] = objtoarray ( $o );
}
}
}
return $obj;
}
/**
* 数组排序
* @param array $arr 需要排序的数组
* @param type $keys
* @param type $type
* @return type
*/
function array_sort($arr,$keys,$type='asc'){
$keysvalue = $new_array = array();
foreach ($arr as $k=>$v){
$keysvalue[$k] = $v[$keys];
}
if($type == 'asc'){
asort($keysvalue);
}else{
arsort($keysvalue);
}
reset($keysvalue);
foreach ($keysvalue as $k=>$v){
$new_array[$k] = $arr[$k];
}
return $new_array;
}
/**
* 获得memcache对象
* @param int $server_id memcache服务器的编号0是本地上的memcache37:37服务器上的memcache2929服务器上的memcache73.73服务器上的memcache
*/
function get_memcache($server_id)
{
$server_id=(int)$server_id;
switch ($server_id)
{
case 0:$server=MEMCACHE_HOST_0;$port=MEMCACHE_PORT_0;
break;
default:;
break;
}
$memcache_obj = memcache_connect($server,$port);
return $memcache_obj;
}
/**
* 产生随机key
* @param int $length key的长度
* @return string
*/
function randomkeys($length)
{
$key = null;
$pattern = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ";
$max = strlen($pattern) - 1;
for($i = 0; $i < $length; $i ++)
{
$key .= $pattern {mt_rand ( 0, $max)};
}
return $key;
}
/**
* 获取浏览器的类型
* @return string
*/
function getbrowsertype()
{
if(strpos($_SERVER ['HTTP_USER_AGENT'],'iPad')||strpos($_SERVER ['HTTP_USER_AGENT'],'iPhone')||strpos($_SERVER ['HTTP_USER_AGENT'],'Android'))
{
$prom_username = $id;
if(strpos($_SERVER ['HTTP_USER_AGENT'], 'Android'))
{
return "android";
}
else
{
return "iphone";
}
}
return "pc";
}
/**
* 获取浏览器的名称
* @return array array('pc'=>$pc,'browser'=>$browser,'ios'=>$ios)
*/
function getbrowsername()
{
$agent=strtolower($_SERVER['HTTP_USER_AGENT']);
$pc=1;
$browser='';
$ios=1;
if(isMobiles())
{
$pc=0;
}
if(strpos($agent,'micromessenger'))
{
$browser='weixin';
}elseif(strpos($agent,'mqqbrowser'))
{
$browser='qq';
}elseif(strpos($agent,'safari'))
{
$browser='safari';
}
elseif(strpos($agent,'chrome'))
{
$browser='chrome';
}
if(strpos($agent,'android'))
{
$ios=0;
}
return array('pc'=>$pc,'browser'=>$browser,'ios'=>$ios);
}
/**
* 检测是移动设备是否是手机
* @return boolean
*/
function isMobiles()
{
// 如果有HTTP_X_WAP_PROFILE则一定是移动设备
if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
{
return true;
}
// 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
if (isset ($_SERVER['HTTP_VIA']))
{
// 找不到为flase,否则为true
return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
}
// 脑残法,判断手机发送的客户端标志,兼容性有待提高
if (isset ($_SERVER['HTTP_USER_AGENT']))
{
$clientkeywords = array ('nokia',
'sony',
'ericsson',
'mot',
'samsung',
'htc',
'sgh',
'lg',
'sharp',
'sie-',
'philips',
'panasonic',
'alcatel',
'lenovo',
'iphone',
'ipod',
'blackberry',
'meizu',
'android',
'netfront',
'symbian',
'ucweb',
'windowsce',
'palm',
'operamini',
'operamobi',
'openwave',
'nexusone',
'cldc',
'midp',
'wap',
'mobile'
);
// 从HTTP_USER_AGENT中查找手机浏览器的关键字
if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
{
return true;
}
}
// 协议法,因为有可能不准确,放到最后判断
if (isset ($_SERVER['HTTP_ACCEPT']))
{
// 如果只支持wml并且不支持html那?欢ㄊ且贫璞?
// 如果支持wml和html但是wml在html之前则是移动设备
if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
{
return true;
}
}
return false;
}
/**
* 固定截取字符串的替换
*/
function new_substr($str,$slen,$ext=""){
global $_G;
if($_G['product']['charset']=="utf-8"){
return utf_substr($str,$slen,$ext);
}else{
return gbk_substr($str,$slen,$ext);
}
}
/**
* gbk编码的字符串截取
* @param string $str 源字符串
* @param int $slen 截取长度
* @param mix $flag 截取字符串起始标志位
* @return string
*/
function gbk_substr($str,$slen,$flag=""){
$restr = "";
$c = "";
$str_len = strlen($str);
$startdd = 0;
if($str_len < $startdd+1) return "";
if($str_len < $startdd + $slen || $slen==0) $slen = $str_len - $startdd;
$enddd = $startdd + $slen - 1;
for($i=0;$i<$str_len;$i++){
if($startdd==0) {
$restr .= $c;
}else if($i > $startdd)
{
$restr .= $c;
}
if(ord($str[$i])>0x80){
if($str_len>$i+1){
$c = $str[$i].$str[$i+1];
}
$i++;
}else{
$c = $str[$i];
}
if($i >= $enddd){
if(strlen($restr)+strlen($c)>$slen){
break;
}else{ $restr .= $c; break; }
}
}
if($restr != $str && $flag) $restr.=$flag;
return $restr;
}
/*
截取字符串
$str 源字符串
$slen 目标长度
$flag 省略符
*/
function utf_substr($str,$len,$flag=""){
if(!$str) return "";
$src=$str;
for($i=0; $i<$len; $i++ ){
$temp_str=substr($str,0,1);
if(ord($temp_str) > 127){
$i++;
if($i<$len){
$new_str[]=substr($str,0,3);
$str=substr($str,3);
}
}else{
$new_str[]=substr($str,0,1);
$str=substr($str,1);
}
}
$new_str=join($new_str);
if( $new_str!==$src && $flag){
$new_str.=$flag;
}
return $new_str;
}
/*
获取数值
$key 索引
$default 默认值
*/
function getnum( $key, $default = 0 ){
$num = getgpc( $key );
$num = is_numeric($num) ? intval($num) : $default;
return $num;
}
/**
* 请求类型
* @param type $k
* @param type $type
* @return type
*/
function getgpc( $k, $type='GP' ){
$type = strtoupper($type);
switch($type) {
case 'G': $var = &$_GET; break;
case 'P': $var = &$_POST; break;
case 'C': $var = &$_COOKIE; break;
default:
if(isset($_GET[$k])) {
$var = &$_GET;
} else {
$var = &$_POST;
}
break;
}
return isset($var[$k]) ? $var[$k] : NULL;
}
/**
*检查链接地址是否有效
*/
function varify_url($url){
$check = @fopen($url,"r");
if($check){
$status = true;
}else{
$status = false;
}
return $status;
}
function myTest($ff){
return $ff['dd'].$ff['ff'];
}
class test{
var $test='';
function __construct() {
echo 'This build';
echo '<br/>';
echo time();
echo '<br/>';
}
function __destruct(){
echo time();
echo '<br/>';
echo 'this destroid';
}
}
/**
* 远程访问验签
* @param type $text
*/
function check_remote_sign($text,$sign){
$key='j674icsngw^%$&Y46fcg0w8r90423ddjvdshfyw$@#%@235frWE%';
$real_sign= md5($key.'_'.$text);
if($sign==$real_sign){
return true;
}else{
return false;
}
}
# 操作间隔限制,存在返回存在内容
function op_limit($key,$timeout=0){
$res=false;
$expire= time()+$timeout;
$memcache_obj = get_memcache(0);
$op_time= memcache_get($memcache_obj,$key);
if(!$op_time){
if($timeout>0){
$result= memcache_set($memcache_obj,$key,1,false,$expire);
}
}
$res=$op_time;
memcache_close($memcache_obj);
return $res;
}
# 操作次数限制,受限返回真
function op_numlimit($key,$times,$timeout=0){
$res=false;
$memcache_obj = get_memcache(0);
$op_time=$memcache_obj->get($key);
if((int)$op_time>=$times)
{
return true;
}
if($timeout>0){
if($op_time===false) {
$memcache_obj->add($key,1,false,$timeout);
}else{
$memcache_obj->increment($key);
}
}
return $res;
}
/**
* 清空memcache
* @param type $key
*/
function clear_memcache($key){
$memcache= get_memcache(0);
$memcache->delete($key);
}
function checkOuth($param){
$sign=$param['sign'];
unset($param['sign']);
unset($param['tp']);
$str= implode(',', $param);
$decrypt=$str.UC_AUTH_KEY;
$cmpSign= md5($decrypt);
if($sign==$cmpSign){
return TRUE;
}else{
return false;
}
}
/**
* 阿里云验签的地址
* @param type $url 需要加密的地址
* @return type
*/
function getCDNURL($url)
{
if(strpos($url,APK_DOMAIN))
{
if(strpos($url,'https')===0)
{
$pro='https';
}else
{
$pro='http';
}
$path=str_replace($pro.'://'.APK_DOMAIN,'',$url);
$time=time();
$stamp=date('YmdHi',$time-27*60);
$sign=md5(CDNKEY.$stamp.$path);
return $pro.'://'.APK_DOMAIN.'/'.$stamp.'/'.$sign.$path;
}
return $url;
}
function curl_post($url, $timeout=10,array $post = array(), array $options = array()){
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_POSTFIELDS => http_build_query($post)
);
$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
/**
* 获取memcache中的值
* @param type $key
* @return type
*/
function getMemcacheVal($key){
$memcache_obj = get_memcache(0);
$result=$memcache_obj->get($key);
$memcache_obj->close();
return $result;
}
/**
* memcache保存
* @param type $key
* @param type $val
* @param type $expire
*/
function save_memcache($key,$val,$expire){
$memcache_obj = get_memcache(0);
$memcache_obj->set($key,$val,0,$expire);
$memcache_obj->close();
}
/**
* 身份证检验
* @param type $id_card
* @return boolean
*/
function validation_filter_id_card($id_card){
if(strlen($id_card)==18){
return idcard_checksum18($id_card);
}elseif((strlen($id_card)==15)){
$id_card=idcard_15to18($id_card);
return idcard_checksum18($id_card);
}else{
return false;
}
}
// 计算身份证校验码根据国家标准GB 11643-1999
function idcard_verify_number($idcard_base){
if(strlen($idcard_base)!=17){
return false;
}
//加权因子
$factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
//校验码对应值
$verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
$checksum=0;
for($i=0;$i<strlen($idcard_base);$i++){
$checksum += substr($idcard_base,$i,1) * $factor[$i];
}
$mod=$checksum % 11;
$verify_number=$verify_number_list[$mod];
return $verify_number;
}
// 将15位身份证升级到18位
function idcard_15to18($idcard){
if(strlen($idcard)!=15){
return false;
}else{
// 如果身份证顺序码是996 997 998 999这些是为百岁以上老人的特殊编码
if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
$idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
}else{
$idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
}
}
$idcard=$idcard.idcard_verify_number($idcard);
return $idcard;
}
// 18位身份证校验码有效性检查
function idcard_checksum18($idcard){
if(strlen($idcard)!=18){
return false;
}
$idcard_base=substr($idcard,0,17);
if(idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
return false;
}else{
return true;
}
}