global.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697
  1. <?php
  2. /*  
  3. * global.php  
  4. * 公共函数库    
  5. * 更新: Jacky.Chen 2013/10/20 15:45  
  6. */
  7. /*
  8. * 返回经addslashes处理过的字符串或数组
  9. * @param $string 需要处理的字符串或数组
  10. * @return mixed
  11. */
  12. function new_add_slashes($string)
  13. {
  14. if(!is_array($string))return addslashes($string);
  15. foreach($string as $key=>$val)
  16. {
  17. $string[$key] = new_add_slashes($val);
  18. }
  19. return $string;
  20. }
  21. /*
  22. * 返回经stripslashes处理过的字符串或数组
  23. * @param $string 需要处理的字符串或数组
  24. * @return mixed
  25. */
  26. function new_stripslashes($string) {
  27. if(!is_array($string)) return stripslashes($string);
  28. foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
  29. return $string;
  30. }
  31. /*
  32. * 返回经htmlspecialchars处理过的字符串或数组
  33. * @param $obj 需要处理的字符串或数组
  34. * @return mixed
  35. */
  36. function new_htmlspecialchars($string) {
  37. if(!is_array($string)) return htmlspecialchars($string);
  38. foreach($string as $key => $val) $string[$key] = new_htmlspecialchars($val);
  39. return $string;
  40. }
  41. //filterkeys 指定了排除在外的键值
  42. function safe_replace_array($array,$filterKeys=array())
  43. {
  44. foreach($array as $k=>$v)
  45. {
  46. if(!in_array($k,$filterKeys)) $array[$k] = safe_replace($v);
  47. }
  48. return $array;
  49. }
  50. /*
  51. * 安全过滤函数
  52. * @parame $string
  53. * @return string
  54. */
  55. function safe_replace($string)
  56. {
  57. $string = str_replace('%20','',$string);
  58. $string = str_replace('%27','',$string);
  59. $string = str_replace('%2527','',$string);
  60. $string = str_replace('*','',$string);
  61. $string = str_replace('"','&quot;',$string);
  62. $string = str_replace("'",'',$string);
  63. $string = str_replace('"','',$string);
  64. $string = str_replace(';','',$string);
  65. $string = str_replace('>','&gt;',$string);
  66. $string = str_replace('<','&lt;',$string);
  67. $string = str_replace('{','',$string);
  68. $string = str_replace('}','',$string);
  69. $string = str_replace('\\','',$string);
  70. return $string;
  71. }
  72. /**
  73. * xss过滤函数
  74. *
  75. * @param $string
  76. * @return string
  77. */
  78. function remove_xss($string) {
  79. $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);
  80. $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
  81. $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
  82. $parm = array_merge($parm1, $parm2);
  83. for ($i = 0; $i < sizeof($parm); $i++) {
  84. $pattern = '/';
  85. for ($j = 0; $j < strlen($parm[$i]); $j++) {
  86. if ($j > 0) {
  87. $pattern .= '(';
  88. $pattern .= '(&#[x|X]0([9][a][b]);?)?';
  89. $pattern .= '|(&#0([9][10][13]);?)?';
  90. $pattern .= ')?';
  91. }
  92. $pattern .= $parm[$i][$j];
  93. }
  94. $pattern .= '/i';
  95. $string = preg_replace($pattern, '', $string);
  96. }
  97. return $string;
  98. }
  99. /**
  100. * 转义 javascript 代码标记
  101. *
  102. * @param $str
  103. * @return mixed
  104. */
  105. function trim_script($str) {
  106. if(is_array($str)){
  107. foreach ($str as $key => $val){
  108. $str[$key] = trim_script($val);
  109. }
  110. }else{
  111. $str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str );
  112. $str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str );
  113. $str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str );
  114. $str = str_replace ( 'javascript:', 'javascript:', $str );
  115. }
  116. return $str;
  117. }
  118. /*
  119. * 过滤ASCII码从0-28的控制字符
  120. * @return String
  121. */
  122. function trim_unsafe_control_chars($str) {
  123. $rule = '/[' . chr ( 1 ) . '-' . chr ( 8 ) . chr ( 11 ) . '-' . chr ( 12 ) . chr ( 14 ) . '-' . chr ( 31 ) . ']*/';
  124. return str_replace ( chr ( 0 ), '', preg_replace ( $rule, '', $str ) );
  125. }
  126. /*
  127. * 格式化文本域内容
  128. *
  129. * @param $string 文本域内容
  130. * @return string
  131. */
  132. function trim_textarea($string) {
  133. $string = nl2br ( str_replace ( ' ', '&nbsp;', $string ) );
  134. return $string;
  135. }
  136. /**
  137. * 安全过滤表单输入
  138. *
  139. * @param $string
  140. * @return string
  141. */
  142. function safe_filter_input($string) {
  143. if(!is_array($string)) {
  144. $string = trim($string);
  145. $string = stripslashes($string);
  146. $string = htmlspecialchars($string);
  147. return $string;
  148. }
  149. foreach($string as $key => $val) {
  150. $val = trim($val);
  151. $val = stripslashes($val);
  152. $val = htmlspecialchars($val);
  153. $string[$key] = $val;
  154. }
  155. return $string;
  156. }
  157. /*
  158. * 将文本格式成适合js输出的字符串
  159. * @param string $string 需要处理的字符串
  160. * @param intval $isjs 是否执行字符串格式化,默认为执行
  161. * @return string 处理后的字符串
  162. */
  163. function format_js($string, $isjs = 1) {
  164. $string = addslashes(str_replace(array("\r", "\n", "\t"), array('', '', ''), $string));
  165. return $isjs ? 'document.write("'.$string.'");' : $string;
  166. }
  167. /*
  168. * 获取当前页面完整URL地址
  169. */
  170. function get_url() {
  171. $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
  172. $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
  173. $path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
  174. $relate_url = isset($_SERVER['REQUEST_URI']) ? safe_replace($_SERVER['REQUEST_URI']) : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
  175. return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
  176. }
  177. /**
  178. * 字符串截取,支持中英文
  179. * @param $str
  180. * @param int $start
  181. * @param $length
  182. * @param string $charset
  183. * @param bool $suffix
  184. * @return false|string
  185. * @author 肆月
  186. */
  187. function str_cut($str, $start = 0, $length, $dot = '...')
  188. {
  189. $charset = CHARSET;
  190. if (function_exists("mb_substr")) {
  191. if ($dot) {
  192. if (strlen($str) > $length)
  193. return mb_substr($str, $start, $length, $charset) . $dot;
  194. else
  195. return mb_substr($str, $start, $length, $charset);
  196. } else {
  197. return mb_substr($str, $start, $length, $charset);
  198. }
  199. } elseif (function_exists('iconv_substr')) {
  200. if ($dot) {
  201. if (strlen($str) > $length)
  202. return iconv_substr($str, $start, $length, $charset). $dot;
  203. else
  204. return iconv_substr($str, $start, $length, $charset);
  205. } else {
  206. return iconv_substr($str, $start, $length, $charset);
  207. }
  208. }
  209. }
  210. //隐藏用户名中间字符仅保留头尾
  211. function hide_user_name($user_name, $repeatStr = '*', $encode = 'utf-8')
  212. {
  213. if (empty($user_name)) {
  214. return '***';
  215. }
  216. $length = mb_strlen($user_name, $encode);
  217. $firstStr = mb_substr($user_name, 0, 1, $encode);
  218. $lastStr = mb_substr($user_name, -1, 1, $encode);
  219. if($length ==1){
  220. return $user_name;
  221. }
  222. return $length == 2 ? $firstStr . str_repeat($repeatStr, $length - 1) : $firstStr . str_repeat($repeatStr, $length - 2) . $lastStr;
  223. }
  224. /*
  225. * 获取请求ip
  226. * @return ip地址(整数形式)
  227. */
  228. function ip() {
  229. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  230. $ip = getenv('HTTP_CLIENT_IP');
  231. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  232. $ip = getenv('HTTP_X_FORWARDED_FOR');
  233. } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  234. $ip = getenv('REMOTE_ADDR');
  235. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  236. $ip = $_SERVER['REMOTE_ADDR'];
  237. }
  238. return preg_match ( '/[\d\.]{7,23}/', $ip, $matches ) ? ip2long($matches [0]) : 0;
  239. }
  240. /*
  241. * 程序执行时间
  242. * @return int 单位ms
  243. *
  244. */
  245. function execute_time() {
  246. $stime = explode ( ' ', SYS_START_TIME );
  247. $etime = explode ( ' ', microtime () );
  248. return number_format ( ($etime [1] + $etime [0] - $stime [1] - $stime [0]), 6 );
  249. }
  250. /*
  251. * 产生随机字符串
  252. * @param int $length 输出长度
  253. * @param string $chars 可选的 ,默认为 0123456789
  254. * @return string 字符串
  255. *
  256. */
  257. function random($length, $chars = '0123456789') {
  258. $hash = '';
  259. $max = strlen($chars) - 1;
  260. for($i = 0; $i < $length; $i++) {
  261. $hash .= $chars[mt_rand(0, $max)];
  262. }
  263. return $hash;
  264. }
  265. /*
  266. * 将字符串转换为数组
  267. * @param string $data 字符串
  268. * @return array 返回数组格式,如果,data为空,则返回空数组
  269. *
  270. */
  271. function string2array($data) {
  272. $array = array();
  273. if($data == '') return array();
  274. eval("\$array = $data;");
  275. return $array;
  276. }
  277. /**
  278. * 将数组转换为字符串
  279. *
  280. * @param array $data 数组
  281. * @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
  282. * @return string 返回字符串,如果,data为空,则返回空
  283. */
  284. function array2string($data, $isformdata = 1) {
  285. if($data == '') return '';
  286. if($isformdata) $data = new_stripslashes($data);
  287. return var_export($data, TRUE);
  288. }
  289. /*
  290. * 转换字节数为其他单位
  291. * @param string $filesize 字节大小
  292. * @return string 返回大小
  293. */
  294. function sizecount($filesize) {
  295. if ($filesize >= 1073741824) {
  296. $filesize = round($filesize / 1073741824 * 100) / 100 .'GB';
  297. } elseif ($filesize >= 1048576) {
  298. $filesize = round($filesize / 1048576 * 100) / 100 .'MB';
  299. } elseif($filesize >= 1024) {
  300. $filesize = round($filesize / 1024 * 100) / 100 . 'KB';
  301. } else {
  302. $filesize = $filesize.'Bytes';
  303. }
  304. return $filesize;
  305. }
  306. /**
  307. * @param int $num 要转换的阿拉伯数字
  308. * @return string 转换成的字符串
  309. */
  310. function numconvert($num)
  311. {
  312. if ($num >= 100000000) {
  313. $num = round($num / 100000000, 1) . '亿+';
  314. } else if ($num >= 10000000) {
  315. $num = round($num / 10000000, 1) . '万+';
  316. } else if ($num >= 10000) {
  317. $num = round($num / 10000, 1) . '万+';
  318. }
  319. return $num;
  320. }
  321. function numconvert2($num)
  322. {
  323. $num = '<span style="font-weight: bold;">'.round($num / 10000, 2) . '</span>万';
  324. return $num;
  325. }
  326. /*
  327. * 对用户密码进行加密,用于后台
  328. * @parame $password
  329. * @parame $encrypt //加密因子
  330. * @return string
  331. *
  332. */
  333. function password($password,$encrypt='')
  334. {
  335. $pwd = array();
  336. $pwd['encrypt'] = $encrypt?$encrypt:random(6, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
  337. $pwd['password'] = md5(md5($password).$pwd['encrypt']);
  338. return $encrypt?$pwd['password']:$pwd;
  339. }
  340. /*
  341. * 判断是否为非法输入
  342. * @parame $string
  343. * return boolean
  344. *
  345. */
  346. function is_bad_word($string)
  347. {
  348. $array = array('"','\\',' ','&','*','#','/','<','>','\r','\t','\n','#',"'");
  349. foreach($array as $value)
  350. {
  351. if(strpos($string,$value)!==false)
  352. {
  353. return true;
  354. }
  355. else
  356. {
  357. return false;
  358. }
  359. }
  360. }
  361. /*
  362. * 对数据进行编码转换
  363. * @param array/string $data 数组
  364. * @param string $input 需要转换的编码
  365. * @param string $output 转换后的编码
  366. *
  367. */
  368. function array_iconv($data,$input='gbk',$output='utf-8')
  369. {
  370. if(!is_array($data))
  371. {
  372. $data = iconv($input,$output."//IGNORE",$data);
  373. }
  374. else
  375. {
  376. foreach($data as $key=>$value)
  377. {
  378. $data[$key] = iconv($input,$output."//IGNORE",$value);
  379. }
  380. }
  381. return $data;
  382. }
  383. /**
  384. * 字符串加密、解密函数
  385. * @param string $txt 字符串
  386. * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
  387. * @param string $key 密钥:数字、字母、下划线
  388. * @param string $expiry 过期时间
  389. * @return string
  390. *
  391. */
  392. function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
  393. $key_length = 4;
  394. $key = md5($key != '' ? $key : AUTH_KEY);
  395. $fixedkey = md5($key);
  396. $egiskeys = md5(substr($fixedkey, 16, 16));
  397. $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
  398. $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
  399. $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
  400. $i = 0; $result = '';
  401. $string_length = strlen($string);
  402. for ($i = 0; $i < $string_length; $i++){
  403. $result .= chr(ord($string[$i]) ^ ord($keys[$i % 32]));
  404. }
  405. if($operation == 'ENCODE') {
  406. return $runtokey . str_replace('=', '', base64_encode($result));
  407. } else {
  408. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
  409. return substr($result, 26);
  410. } else {
  411. return '';
  412. }
  413. }
  414. }
  415. // 函数返回当前 Unix 时间戳和微秒数
  416. function getmicrotime() {
  417. list($usec, $sec) = explode(" ",microtime());
  418. return ((float)$usec + (float)$sec);
  419. }
  420. /*
  421. * 取得文件扩展
  422. * @param $filename 文件名
  423. * @return 扩展名
  424. *
  425. */
  426. function fileext($filename) {
  427. return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
  428. }
  429. /**
  430. * 查询字符是否存在于某字符串
  431. *
  432. * @param $haystack 字符串
  433. * @param $needle 要查找的字符
  434. * @return bool
  435. */
  436. function str_exists($haystack, $needle)
  437. {
  438. return !(strpos($haystack, $needle) === FALSE);
  439. }
  440. //判断远程文件
  441. function check_remote_file_exists($url)
  442. {
  443. $handle = @fopen($url, 'r');
  444. if(!$handle){
  445. return false;
  446. }else{
  447. return true;
  448. }
  449. }
  450. function check_remote_file_exists1($url)
  451. {
  452. $curl = curl_init();
  453. curl_setopt($curl, CURLOPT_URL, $url);
  454. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  455. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  456. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
  457. curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
  458. // 不取回数据
  459. curl_setopt($curl, CURLOPT_NOBODY, true);
  460. // 发送请求
  461. $result = curl_exec($curl);
  462. $found = false;
  463. // 如果请求没有发送失败
  464. if ($result !== false)
  465. {
  466. // 再检查http响应码是否为200
  467. $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  468. if ($statusCode == 200)
  469. {
  470. $found = true;
  471. }
  472. }
  473. curl_close($curl);
  474. return $found;
  475. }
  476. //获取远程文件大小
  477. function remote_file_size($url)
  478. {
  479. $curl = curl_init();
  480. curl_setopt($curl, CURLOPT_URL, $url);
  481. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  482. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  483. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
  484. curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
  485. // 不取回数据
  486. curl_setopt($curl, CURLOPT_NOBODY, true);
  487. // 发送请求
  488. $result = curl_exec($curl);
  489. $size = 0;
  490. // 如果请求没有发送失败
  491. if ($result !== false)
  492. {
  493. $size = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
  494. }
  495. curl_close($curl);
  496. return $size;
  497. }
  498. /*
  499. * 判断是否为图片
  500. *
  501. */
  502. function is_image($file) {
  503. $ext_arr = array('jpg','gif','png','bmp','jpeg','tiff');
  504. $ext = fileext($file);
  505. return in_array($ext,$ext_arr) ? $ext_arr :false;
  506. }
  507. /*
  508. * 判断是否为视频
  509. *
  510. */
  511. function is_video($file) {
  512. $ext_arr = array('rm','mpg','avi','mpeg','wmv','flv','asf','rmvb');
  513. $ext = fileext($file);
  514. return in_array($ext,$ext_arr) ? $ext_arr :false;
  515. }
  516. //保存远程图片
  517. function save_remote_file($remote_url,$local_path)
  518. {
  519. $file = https_request($remote_url);
  520. file_put_contents($local_path,$file);
  521. return $local_path;
  522. }
  523. //根据路径判断是否网络文件
  524. function is_net_file($url)
  525. {
  526. if(preg_match('/^https?.*$/',$url))//网络文件
  527. {
  528. return true;
  529. }
  530. else
  531. {
  532. return false;
  533. }
  534. }
  535. /*
  536. * 检查id是否存在于数组中
  537. * @param $id
  538. * @param $ids
  539. * @param $s
  540. *
  541. */
  542. function check_in($id, $ids = '', $s = ',') {
  543. if(!$ids) return false;
  544. $ids = explode($s, $ids);
  545. return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
  546. }
  547. //判断目录是否可写
  548. function dir_writeable($dir) {
  549. $writeable = 0;
  550. if(is_dir($dir)) {
  551. if($fp = @fopen("$dir/chkdir.test", 'w')) {
  552. @fclose($fp);
  553. @unlink("$dir/chkdir.test");
  554. $writeable = 1;
  555. } else {
  556. $writeable = 0;
  557. }
  558. }
  559. return $writeable;
  560. }
  561. /**
  562. * 图片水印:gif,jpeg,png
  563. * @param $imgSrc
  564. * @param $markImg:水印图
  565. * @param $markPos:水印位置 0:随机位置,在1~9之间随机选取一个位置
  566. 1:顶部居左 2:顶部居中 3:顶部居右 4:左边居中
  567. 5:图片中心 6:右边居中 7:底部居左 8:底部居中 9:底部居右 10:铺满
  568. */
  569. function set_img_water($imgSrc,$markImg,$markQty=100,$markPos=9){
  570. if(intval($markQty)==0)$markQty=100;
  571. if($markPos==10)
  572. {
  573. $im = imagecreatefromstring(file_get_contents($imgSrc));
  574. //获取水印源
  575. $watermark = imagecreatefromstring(file_get_contents($markImg));
  576. //获取图、水印 宽高类型
  577. list($bgWidth, $bgHight, $bgType) = getimagesize($imgSrc);
  578. list($logoWidth, $logoHight, $logoType) = getimagesize($markImg);
  579. //定义平铺数据
  580. $x_length = $bgWidth - 10; //x轴总长度
  581. $y_length = $bgHight - 10; //y轴总长度
  582. //创建透明画布 伪白色
  583. $opacity=30;
  584. $w = imagesx($watermark);
  585. $h = imagesy($watermark);
  586. $bigw = $w*2;
  587. $bigh = $h*2;
  588. $cut = imagecreatetruecolor($bigw,$bigh);
  589. $white = imagecolorallocatealpha($cut, 255,255,255,0);
  590. imagefill( $cut, 0, 0, $white );
  591. //整合水印
  592. //imagecopy($cut, $watermark, 0, 0, 0, 0, $w, $h);
  593. imagecopyresampled($cut,$watermark,0,0,0,0,$bigw,$bigh,$w,$h);
  594. //设定目标画布
  595. $dst_img = @imagecreatetruecolor($bgWidth, $bgHight);
  596. //上色
  597. $color = imagecolorallocate($dst_img, 255, 255, 255);
  598. imagefill($dst_img, 0, 0, $color);
  599. //循环平铺水印
  600. for ($x = 0; $x < $x_length; $x++)
  601. {
  602. for ($y = 0; $y < $y_length; $y++) {
  603. imagecopymerge($dst_img, $cut, $x, $y, 0, 0, $bigw, $bigh, $opacity);
  604. $y += ($logoHight+200);
  605. }
  606. $x += ($logoWidth+200);
  607. }
  608. //header("Content-type:image/png");
  609. imagecopy($dst_img, $im, 0, 0, 0, 0, $bgWidth, $bgHight);
  610. //imagepng($dst_img,$imgSrc);
  611. switch ($bgType)
  612. {
  613. case 1: imagegif($dst_img, $imgSrc); break;
  614. case 2: imagejpeg($dst_img, $imgSrc);break;
  615. case 3: imagepng($dst_img, $imgSrc); break;
  616. default: break;
  617. }
  618. imagedestroy($im);
  619. imagedestroy($dst_img);
  620. imagedestroy($cut);
  621. return true;
  622. }
  623. else
  624. {
  625. $srcInfo = @getimagesize($imgSrc);
  626. $srcImg_w = $srcInfo[0];
  627. $srcImg_h = $srcInfo[1];
  628. $srcim = null; $markim = null;
  629. switch ($srcInfo[2])
  630. {
  631. case 1:
  632. $srcim =imagecreatefromgif($imgSrc); break;
  633. case 2:
  634. $srcim =imagecreatefromjpeg($imgSrc); break;
  635. case 3:
  636. $srcim =imagecreatefrompng($imgSrc); break;
  637. default:
  638. die('unsupport file type'); exit();
  639. }
  640. if(!file_exists($markImg) || empty($markImg)){return;}
  641. $markImgInfo = @getimagesize($markImg);
  642. $markImg_w = $markImgInfo[0];
  643. $markImg_h = $markImgInfo[1];
  644. if($srcImg_w < $markImg_w || $srcImg_h < $markImg_h){return false;}
  645. switch ($markImgInfo[2])
  646. {
  647. case 1:
  648. $markim =imagecreatefromgif($markImg); break;
  649. case 2:
  650. $markim =imagecreatefromjpeg($markImg); break;
  651. case 3:
  652. $markim =imagecreatefrompng($markImg); break;
  653. default:
  654. return false;//die('不支持的水印图片文件类型');exit();
  655. }
  656. $logow = $markImg_w;
  657. $logoh = $markImg_h;
  658. if($markPos == 0){$markPos = rand(1, 9);}
  659. switch($markPos)
  660. {
  661. case 1: $x = +5; $y = +5; break;//顶部居左
  662. case 2: $x = ($srcImg_w-$logow)/2; $y = +5; break;//顶部居中
  663. case 3: $x = $srcImg_w- $logow-5; $y = +15; break;//顶部居右
  664. case 4: $x = +5; $y = ($srcImg_h-$logoh)/2; break;//左边居中
  665. case 5: $x = ($srcImg_w-$logow)/2; $y = ($srcImg_h-$logoh)/2; break;//图片中心
  666. case 6: $x = $srcImg_w-$logow-5; $y = ($srcImg_h-$logoh)/2; break;//右边居中
  667. case 7: $x = +5; $y = $srcImg_h-$logoh-5; break;//底部居左
  668. case 8: $x = ($srcImg_w-$logow)/2; $y = $srcImg_h-$logoh-5; break;//底部居中
  669. case 9: $x = $srcImg_w-$logow-5; $y = $srcImg_h-$logoh-5; break;//底部居右
  670. default:
  671. return false;//die('此位置不支持');exit;
  672. }
  673. $dst_img = @imagecreatetruecolor($srcImg_w, $srcImg_h);
  674. //上色
  675. $color = imagecolorallocate($dst_img, 255, 255, 255);
  676. imagefill($dst_img, 0, 0, $color);
  677. imagecopy($dst_img, $srcim, 0, 0, 0, 0, $srcImg_w, $srcImg_h);
  678. imagecopy($dst_img, $markim, $x, $y, 0, 0, $logow, $logoh);
  679. imagedestroy($markim);
  680. switch ($srcInfo[2])
  681. {
  682. case 1: imagegif($dst_img, $imgSrc); break;
  683. case 2: imagejpeg($dst_img, $imgSrc);break;
  684. case 3: imagepng($dst_img, $imgSrc); break;
  685. default: break;
  686. }
  687. imagedestroy($dst_img);
  688. imagedestroy($srcim);
  689. return true;
  690. }
  691. }
  692. //获取一个唯一文件名
  693. function get_unique_file_name($path,$ext)
  694. {
  695. $fileName = TIMESTAMP.random(6, '0123456789abcdefghijklmnopqrstuvwxyz').".".$ext;//文件重命名
  696. if(!file_exists($path.$fileName))
  697. {
  698. return $fileName;
  699. }
  700. else
  701. {
  702. return get_unique_file_name($path,$ext);
  703. }
  704. }
  705. //转换数组为可适应SQL语句插入语法值集合
  706. function change_array_to_sql_string($array=array()){ //转换数组为可适应SQL语句插入语法值集合
  707. $array=str_replace("'","\'",$array);
  708. return "'".implode("','",$array)."'";
  709. }
  710. // 截取某部分字符
  711. function interception_of_string($string='',$start='',$end='')
  712. {
  713. if($string==''){return '';}
  714. if($start!='')
  715. {
  716. $pos = strpos($string,$start);
  717. if($pos===false)
  718. {
  719. return '';
  720. }
  721. else
  722. {
  723. $pos += strlen($start);
  724. $string = substr($string,$pos);
  725. }
  726. }
  727. if($end!='')
  728. {
  729. $pos = strpos($string,$end);
  730. if($pos)
  731. {
  732. $string = substr($string,0,$pos);
  733. }
  734. }
  735. return $string;
  736. }
  737. //Curl
  738. function https_request($url,$options = null,$data = null,$header = null){
  739. $curl = curl_init();
  740. curl_setopt($curl, CURLOPT_URL, $url);
  741. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  742. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  743. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
  744. curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
  745. if (!empty($data)){
  746. curl_setopt($curl, CURLOPT_POST, 1);
  747. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
  748. }
  749. (isset($options['header'])&&$options['header'])?curl_setopt($curl, CURLOPT_HEADER, 1): curl_setopt($curl, CURLOPT_HEADER, 0);//如果有响应头
  750. if(!empty($header))//如果有请求头
  751. {
  752. $curl_header = array();
  753. foreach($header as $key=>$value)
  754. {
  755. $curl_header[] = "$key:$value";
  756. }
  757. curl_setopt($curl,CURLOPT_HTTPHEADER, $curl_header);
  758. }
  759. if(isset($options['gzip'])&&$options['gzip']==1) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); //如果页面开启了GZIP压缩
  760. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  761. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0');
  762. if(!empty($options['time_out']))
  763. {
  764. curl_setopt($curl, CURLOPT_TIMEOUT, $options['time_out']);
  765. }
  766. else
  767. {
  768. curl_setopt($curl, CURLOPT_TIMEOUT, 15);
  769. }
  770. curl_setopt ($curl, CURLOPT_REFERER, get_url());
  771. $output = curl_exec($curl);
  772. curl_close($curl);
  773. return $output;
  774. }
  775. /**批量替换敏感词
  776. * @param array $badwords 敏感词数组
  777. * @param array $replacement 替换词数组
  778. * @param string $str 待替换内容
  779. * @return string
  780. */
  781. function multi_replace($badwords,$replacement,$str)
  782. {
  783. $replaceList = array();
  784. if(is_array($badwords))
  785. {
  786. foreach($badwords as $badword)
  787. {
  788. $length = mb_strlen($badword,CHARSET);
  789. $temp='';
  790. for($i=0;$i<$length;$i++)
  791. {
  792. $temp .= $replacement;
  793. }
  794. $replaceList[] = $temp;
  795. }
  796. }
  797. return $str = str_replace($badwords,$replaceList,$str);
  798. }
  799. /**封装后的配置文件包含方法
  800. */
  801. function require_config($file)
  802. {
  803. if(defined('SITE_MODE'))
  804. {
  805. return require BASE_PATH.'config'.DIRECTORY_SEPARATOR.SITE_MODE.DIRECTORY_SEPARATOR.$file;
  806. }
  807. else
  808. {
  809. return require BASE_PATH.'config'.DIRECTORY_SEPARATOR.$file;
  810. }
  811. }
  812. //格式正则校验
  813. function pattern_check($type,$value)
  814. {
  815. switch($type)
  816. {
  817. case 'url':
  818. $pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
  819. break;
  820. case 'email':
  821. $pattern = '/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/';
  822. break;
  823. default:break;
  824. }
  825. if(!empty($pattern)&&preg_match($pattern,$value)){
  826. return true;
  827. }
  828. else{
  829. return false;
  830. }
  831. }
  832. //请求安全检测
  833. function check_safe_request_params(){
  834. $getfilter="'|<[^>]*?>|^\\+\/v(8|9)|\\b(and|or)\\b.+?(>|<|=|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
  835. $postfilter="^\\+\/v(8|9)|\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|<\\s*img\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
  836. $cookiefilter="\\b(and|or)\\b.{1,6}?(=|>|<|\\bin\\b|\\blike\\b)|\\/\\*.+?\\*\\/|<\\s*script\\b|\\bEXEC\\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\\s+(TABLE|DATABASE)";
  837. $referer=empty($_SERVER['HTTP_REFERER']) ? array() : array($_SERVER['HTTP_REFERER']);
  838. foreach($_GET as $key=>$value){
  839. if (!check_request_params_ok($key,$value,$getfilter)){exit;}
  840. }
  841. foreach($_POST as $key=>$value){
  842. if (!check_request_params_ok($key,$value,$postfilter)){exit;}
  843. }
  844. foreach($_COOKIE as $key=>$value){
  845. if (!check_request_params_ok($key,$value,$cookiefilter)){exit;}
  846. }
  847. foreach($referer as $key=>$value){
  848. if (!check_request_params_ok($key,$value,$getfilter)){exit;}
  849. }
  850. }
  851. //请求安全检测:子方法
  852. function check_request_params_ok($StrFiltKey,$StrFiltValue,$ArrFiltReq){
  853. $StrFiltValue=arr_foreach($StrFiltValue);
  854. if (preg_match('/'.$ArrFiltReq.'/is',$StrFiltValue)==1 || preg_match('/'.$ArrFiltReq.'/is',$StrFiltKey)==1){return false;}
  855. return true;
  856. }
  857. function arr_foreach($arr) {
  858. static $str;
  859. if (!is_array($arr)) {return $arr;}
  860. foreach ($arr as $key => $val ) {
  861. if (is_array($val)) {arr_foreach($val);} else {$str[] = $val;}
  862. }
  863. return implode($str);
  864. }
  865. //带超时时间设置的file_get_contents
  866. function new_file_get_contents($url,$timeout=null)
  867. {
  868. if(isset($timeout))
  869. {
  870. $opts = array(
  871. 'http'=>array(
  872. 'method'=>"GET",
  873. 'timeout'=>$timeout,//单位秒
  874. )
  875. );
  876. return file_get_contents( $url, false, stream_context_create($opts));
  877. }
  878. else
  879. {
  880. return file_get_contents($url);
  881. }
  882. }
  883. //判断是否蜘蛛请求
  884. function checkrobot($useragent = '') {
  885. static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla','haosouspider','baidu','sogou','yisouspider','360spider','baiduspide','soso','yahoo','bingbot');
  886. static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
  887. $useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
  888. if(strpos($useragent, 'http://') === false && strpos($useragent, 'https://') === false && dstrpos($useragent, $kw_browsers)) return false;
  889. if(dstrpos($useragent, $kw_spiders)) return true;
  890. return false;
  891. }
  892. function dstrpos($string, &$arr, $returnvalue = false) {
  893. if(empty($string)) return false;
  894. foreach((array)$arr as $v) {
  895. if(strpos($string, $v) !== false) {
  896. $return = $returnvalue ? $v : true;
  897. return $return;
  898. }
  899. }
  900. return false;
  901. }
  902. //压缩html
  903. function compress_html($str){
  904. $str = trim($str);
  905. $str = str_replace("\t","",$str);
  906. $str = str_replace("\r\n","",$str);
  907. $str = str_replace("\r","",$str);
  908. $str = str_replace("\n","",$str);
  909. $str=preg_replace("/>[ ]+/si",">",$str); //过滤>(">"号后面带空格)
  910. $str=preg_replace("/[ ]+</si","<",$str); //过滤<("<"号前面带空格)
  911. return trim($str);
  912. }
  913. //字符串过滤,只保留汉字数字英文标点符号
  914. function removeHtml($html,$filter=1)
  915. {
  916. $html = htmlspecialchars_decode($html); //把一些预定义的 HTML 实体转换为字符
  917. $html = strip_tags($html); //函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
  918. $html = trim($html); //清除字符串两边的空格
  919. $html = str_replace("&nbsp;","",$html);
  920. $html = preg_replace("/\t/","",$html); //使用正则表达式替换内容,如:空格,换行,并将替换为空。
  921. $html = preg_replace("/\r\n/","",$html);
  922. $html = preg_replace("/\r/","",$html);
  923. $html = preg_replace("/\n/","",$html);
  924. $html = preg_replace("/ /","",$html);
  925. $html = preg_replace("/ /","",$html); //匹配html中的空格
  926. $html = preg_replace('/($s*$)|(^s*^)/m', '',$html);
  927. if($filter)
  928. {
  929. preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()]/u', $html, $result);
  930. return implode('', $result[0]);
  931. }
  932. else
  933. {
  934. return $html;
  935. }
  936. }
  937. //对转换过程中获取的内容做初始处理
  938. function beforeProcessHtml($html)
  939. {
  940. preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u', $html, $testResult);
  941. if(empty($testResult[0]))
  942. {
  943. $html = mb_convert_encoding($html, 'UTF-8', 'UTF-8');
  944. preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()]/u', $html, $result);
  945. return implode('', $result[0]);
  946. }
  947. else
  948. {
  949. return $html;
  950. }
  951. }
  952. //获取所有的cookie内容
  953. function get_all_cookie_str(){
  954. $ckeStr='';
  955. foreach ($_COOKIE as $ckeName=>$ckeVal){
  956. if(!is_array($ckeVal)){
  957. $ckeStr.= $ckeName.'='.$ckeVal.';';
  958. }
  959. }
  960. $ckeStr = substr($ckeStr, 0,-1);//去除最后的 ;
  961. return $ckeStr;
  962. }
  963. //PHP默认serialize有时会出错 http://us.php.net/manual/en/function.unserialize.php#71270
  964. function mb_unserialize($serial_str) {
  965. $serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
  966. $serial_str= str_replace("\r", "", $serial_str);
  967. return unserialize($serial_str);
  968. }
  969. //判断是否是移动端访问
  970. function check_mobile($debug = false) {
  971. static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
  972. 'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
  973. 'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
  974. 'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
  975. 'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
  976. 'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
  977. 'benq', 'haier', '^lct', '320x320', '240x320', '176x220');
  978. static $mobilebrowser_list =array('windows phone');
  979. static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
  980. 'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
  981. 'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
  982. $pad_list = array('pad', 'gt-p1000');
  983. $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  984. if(($v = dstrpos($useragent, $mobilebrowser_list, true))){
  985. return '1'; //windows phone
  986. }
  987. if(($v = dstrpos($useragent, $touchbrowser_list, true))){
  988. return '2';
  989. }
  990. if(($v = dstrpos($useragent, $wmlbrowser_list))) {
  991. return '3'; //wml版
  992. }
  993. $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
  994. if(dstrpos($useragent, $brower)) return false;
  995. return false;
  996. }
  997. //时间换算
  998. function info_last_time($time,$ac="Y年m月d日") {
  999. $now=TIMESTAMP-$time;
  1000. $timestr = (substr_count($ac,'-')>0?'Y-m-d':'Y年m月d日');
  1001. if ($now>3456000) return get_date($time,$timestr);
  1002. elseif ($now>345600) return get_date($time,$ac);
  1003. elseif ($now>259200) return "三天前";
  1004. elseif ($now>172800) return "两天前";
  1005. elseif ($now>86400) return "一天前";
  1006. elseif ($now>72000) return "二十小时前";
  1007. elseif ($now>54000) return "十五小时前";
  1008. elseif ($now>43200) return "十二小时前";
  1009. elseif ($now>36000) return "十小时前";
  1010. elseif ($now>28800) return "八小时前";
  1011. elseif ($now>21600) return "六小时前";
  1012. elseif ($now>18000) return "五小时前";
  1013. elseif ($now>10800) return "三小时前";
  1014. elseif ($now>7200) return "两小时前";
  1015. elseif ($now>3600) return "一小时前";
  1016. elseif ($now>1800) return "半小时前";
  1017. elseif ($now>1200) return "二十分钟前";
  1018. elseif ($now>900) return "十五分钟前";
  1019. elseif ($now>600) return "十分钟前";
  1020. elseif ($now>300) return "五分钟前";
  1021. elseif ($now>180) return "三分钟前";
  1022. elseif ($now>120) return "两分钟前";
  1023. elseif ($now>=0) return "一分钟前";
  1024. elseif ($now<0) return "一秒钟前";
  1025. return get_date($time,$ac);
  1026. }
  1027. /**
  1028. * 格式化时间戳为日期字符串
  1029. * @global string $db_datefm
  1030. * @global string $db_timedf
  1031. * @global string $_datefm
  1032. * @global string $_timedf
  1033. * @param int $timestamp
  1034. * @param string $format
  1035. * @return string
  1036. */
  1037. function get_date($timestamp, $format = null) {
  1038. if(empty($timestamp))return '';
  1039. $obj = new \DateTime("@$timestamp"); // 这里时间戳前要写一个@符号
  1040. $timezone = timezone_open(TIME_ZONE); // 设置时区
  1041. $obj->setTimezone($timezone);
  1042. $sDefaultFormat = $format ? $format : 'Y-m-d H:i';
  1043. return $obj->format($sDefaultFormat);
  1044. }
  1045. //日期转时间戳
  1046. function str_to_time($str)
  1047. {
  1048. $date = new \DateTime($str);
  1049. return $date->format('U');
  1050. }
  1051. //301跳转
  1052. function header_goto($str) {
  1053. Header("HTTP/1.1 301 Moved Permanently");
  1054. Header($str);exit;
  1055. }
  1056. /**
  1057. * 截断字符串
  1058. *
  1059. * @param string $content 内容
  1060. * @param int $length 截取字节数
  1061. * @param string $add 是否带省略号,Y|N
  1062. * @return string
  1063. */
  1064. function substrs($content, $length, $add = 'Y') {
  1065. if (strlen($content) > $length) {
  1066. if (CHARSET != 'utf-8') {
  1067. $cutStr = '';
  1068. for ($i = 0; $i < $length - 1; $i++) {
  1069. $cutStr .= ord($content[$i]) > 127 ? $content[$i] . $content[++$i] : $content[$i];
  1070. }
  1071. $i < $length && ord($content[$i]) <= 127 && $cutStr .= $content[$i];
  1072. return $cutStr . ($add == 'Y' ? ' ..' : '');
  1073. }
  1074. return utf8_trim(substr($content, 0, $length)) . ($add == 'Y' ? ' ..' : '');
  1075. }
  1076. return $content;
  1077. }
  1078. /**
  1079. * utf8字符串整齐化
  1080. *
  1081. * @param string $str
  1082. * @return string
  1083. */
  1084. function utf8_trim($str) {
  1085. $hex = '';
  1086. $len = strlen($str) - 1;
  1087. for ($i = $len; $i >= 0; $i -= 1) {
  1088. $ch = ord($str[$i]);
  1089. $hex .= " $ch";
  1090. if (($ch & 128) == 0 || ($ch & 192) == 192) {return substr($str, 0, $i);}
  1091. }
  1092. return $str . $hex;
  1093. }
  1094. function echo_json($arr){
  1095. ob_clean();
  1096. header('Content-type: application/json');
  1097. echo json_encode($arr);exit;
  1098. }
  1099. //生成唯一订单号
  1100. function getUniOrderNo()
  1101. {
  1102. $order_id = get_date(TIMESTAMP,'Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  1103. $exists = \app\modules\shopping\models\ShoppingOrder::find()->where("order_sn='".$order_id."'")->exists();
  1104. if($exists)
  1105. {
  1106. return getUniOrderNo();
  1107. }
  1108. else
  1109. {
  1110. return $order_id;
  1111. }
  1112. }
  1113. //生成唯一券号
  1114. function getUniCouponNo()
  1115. {
  1116. $coupon_no = get_date(TIMESTAMP,'Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  1117. $exists = \app\modules\ucenter\models\UserVipCoupon::find()->where("coupon_no='".$coupon_no."'")->exists();
  1118. if($exists)
  1119. {
  1120. return getUniCouponNo();
  1121. }
  1122. else
  1123. {
  1124. return $coupon_no;
  1125. }
  1126. }
  1127. //生成唯一订单号(毫秒级)
  1128. function getProUniOrderNo()
  1129. {
  1130. $order_id_main = get_date(TIMESTAMP,'YmdHis') . rand(10,99);
  1131. $order_id_len = strlen($order_id_main);
  1132. $order_id_sum = 0;
  1133. for($i=0; $i<$order_id_len; $i++){
  1134. $order_id_sum += (int)(substr($order_id_main,$i,1));
  1135. }
  1136. $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
  1137. return $order_id;
  1138. }
  1139. /**
  1140. * 二維数组排序
  1141. */
  1142. function array_sort($arr,$sort)
  1143. {
  1144. /* $sort = array(
  1145. 'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
  1146. 'field' => 'length', //排序字段
  1147. );*/
  1148. $arrSort = array();
  1149. foreach($arr AS $uniqid => $row){
  1150. foreach($row AS $key=>$value){
  1151. $arrSort[$key][$uniqid] = $value;
  1152. }
  1153. }
  1154. if($sort['direction']){
  1155. array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arr);
  1156. }
  1157. return $arr;
  1158. }
  1159. /**
  1160. * 可以统计中文字符串长度的函数
  1161. * @param $str 要计算长度的字符串
  1162. * @param $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符
  1163. */
  1164. function abslength($str)
  1165. {
  1166. if(empty($str)){
  1167. return 0;
  1168. }
  1169. if(function_exists('mb_strlen')){
  1170. return mb_strlen($str,'utf-8');
  1171. }
  1172. else {
  1173. preg_match_all("/./u", $str, $ar);
  1174. return count($ar[0]);
  1175. }
  1176. }
  1177. //过滤微信表情
  1178. function filterEmoji($nickname)
  1179. {
  1180. $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickname);
  1181. $nickname = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nickname);
  1182. $nickname = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nickname);
  1183. $nickname = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nickname);
  1184. $nickname = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nickname);
  1185. $nickname = str_replace(array('"','\''), '', $nickname);
  1186. return $nickname;
  1187. }
  1188. //单条对象记录转数组
  1189. function single_object_to_array($result,$needfield = array())
  1190. {
  1191. $info = array();
  1192. if(is_object($result))
  1193. {
  1194. foreach($result as $key=>$value)
  1195. {
  1196. if(!empty($needfield)&&in_array($key,$needfield))
  1197. {
  1198. $info[$key] = $value;
  1199. }
  1200. if(empty($needfield))
  1201. {
  1202. $info[$key] = $value;
  1203. }
  1204. }
  1205. return $info;
  1206. }
  1207. else
  1208. {
  1209. return $result;
  1210. }
  1211. }
  1212. //获得文件绝对路径
  1213. function getFileUrl($path,$internal=0)
  1214. {
  1215. if(empty($path)) return;
  1216. if(strpos($path,'http')!==false)
  1217. {
  1218. $path = str_replace(array('https://','http://'),array(SITE_PROTOCOL,SITE_PROTOCOL),$path);
  1219. }
  1220. else
  1221. {
  1222. //如果开启了OSS
  1223. if(Yii::$app->params['oss']['OPEN_OSS'])
  1224. {
  1225. if($internal==1)
  1226. {
  1227. $path = getOssInterUrl().$path;
  1228. }
  1229. else
  1230. {
  1231. $path = getOssUrl().$path;
  1232. }
  1233. }
  1234. else
  1235. {
  1236. $path = UPLOAD_URL.$path;
  1237. }
  1238. }
  1239. if(IN_WAP)
  1240. {
  1241. $path = str_replace(WEB_URL,WAP_URL,$path);
  1242. }
  1243. return $path;
  1244. }
  1245. //获得文件转换结果路径
  1246. function getFileWorkPath($file)
  1247. {
  1248. $result = parse_url($file);
  1249. $path= str_replace('/upload/','',$result['path']);
  1250. $ext = fileext($path);
  1251. $workpath = dirname($path).DIRECTORY_SEPARATOR.md5(basename($path,'.'.$ext)).DIRECTORY_SEPARATOR;
  1252. $workpath = ltrim(str_replace(DIRECTORY_SEPARATOR,'/',$workpath),'/');
  1253. return $workpath;
  1254. }
  1255. //获得文件相对路径
  1256. function getFilePath($file)
  1257. {
  1258. $result = parse_url($file);
  1259. $path= str_replace('/upload/','',$result['path']);
  1260. return $path;
  1261. }
  1262. function unserializeFileRealUrl($string,$first=true)
  1263. {
  1264. $fileList = string2array($string);
  1265. $urls = '';
  1266. if($first)
  1267. {
  1268. if(isset($fileList['filepath']))
  1269. {
  1270. if(!empty($fileList['filepath']))
  1271. {
  1272. $urls = getFileUrl($fileList['filepath']);
  1273. }
  1274. }
  1275. else
  1276. {
  1277. if(!empty($fileList[0]['filepath']))
  1278. {
  1279. if(strpos($fileList[0]['fileurl'],'http')!==false)
  1280. {
  1281. return $fileList[0]['fileurl'];
  1282. }
  1283. else
  1284. {
  1285. $urls = getFileUrl($fileList[0]['filepath']);
  1286. }
  1287. }
  1288. }
  1289. }
  1290. else
  1291. {
  1292. $urls = array();
  1293. if(is_array($fileList))foreach($fileList as $file)
  1294. {
  1295. if(!empty($file['filepath']))$urls[] = getFileUrl($file['filepath']);
  1296. }
  1297. }
  1298. return $urls;
  1299. }
  1300. //判断是否是手机站
  1301. function is_wap_site()
  1302. {
  1303. if(IN_WAP==true)
  1304. {
  1305. return true;
  1306. }
  1307. else
  1308. {
  1309. return false;
  1310. }
  1311. }
  1312. //判断是IOS或安卓系统
  1313. function get_device_type()
  1314. {
  1315. //全部变成小写字母
  1316. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1317. $type ='other';
  1318. //分别进行判断
  1319. if(strpos($agent,'iphone') || strpos($agent,'ipad'))
  1320. {
  1321. $type ='ios';
  1322. }
  1323. if(strpos($agent,'android'))
  1324. {
  1325. $type ='android';
  1326. }
  1327. return $type;
  1328. }
  1329. //判断是否是微信访问
  1330. function check_micromsg()
  1331. {
  1332. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1333. if (stripos($agent, 'MicroMessenger') !== false)
  1334. {
  1335. return true;
  1336. } else {
  1337. return false;
  1338. }
  1339. }
  1340. //判断是否是百度小程序访问
  1341. function check_baiduapp()
  1342. {
  1343. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1344. if (stripos($agent, 'baiduboxapp') !== false)
  1345. {
  1346. return true;
  1347. } else {
  1348. return false;
  1349. }
  1350. }
  1351. //判断是否是微信小程序访问
  1352. function check_wxapp()
  1353. {
  1354. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1355. if (stripos($agent, 'miniprogram') !== false)
  1356. {
  1357. return true;
  1358. } else {
  1359. return false;
  1360. }
  1361. }
  1362. /*
  1363. * 作用:用*号替代姓名除第一个字之外的字符
  1364. * 参数:
  1365. *
  1366. *
  1367. * 返回值:string
  1368. */
  1369. function starReplace($name, $num = 0)
  1370. {
  1371. if ($num && mb_strlen($name, 'UTF-8') > $num) {
  1372. return mb_substr($name, 0, 4) . '*';
  1373. }
  1374. if ($num && mb_strlen($name, 'UTF-8') <= $num) {
  1375. return $name;
  1376. }
  1377. $doubleSurname = [
  1378. '欧阳', '太史', '端木', '上官', '司马', '东方', '独孤', '南宫',
  1379. '万俟', '闻人', '夏侯', '诸葛', '尉迟', '公羊', '赫连', '澹台', '皇甫', '宗政', '濮阳',
  1380. '公冶', '太叔', '申屠', '公孙', '慕容', '仲孙', '钟离', '长孙', '宇文', '司徒', '鲜于',
  1381. '司空', '闾丘', '子车', '亓官', '司寇', '巫马', '公西', '颛孙', '壤驷', '公良', '漆雕', '乐正',
  1382. '宰父', '谷梁', '拓跋', '夹谷', '轩辕', '令狐', '段干', '百里', '呼延', '东郭', '南门', '羊舌',
  1383. '微生', '公户', '公玉', '公仪', '梁丘', '公仲', '公上', '公门', '公山', '公坚', '左丘', '公伯',
  1384. '西门', '公祖', '第五', '公乘', '贯丘', '公皙', '南荣', '东里', '东宫', '仲长', '子书', '子桑',
  1385. '即墨', '达奚', '褚师', '吴铭'
  1386. ];
  1387. $surname = mb_substr($name, 0, 2);
  1388. if (in_array($surname, $doubleSurname)) {
  1389. $name = mb_substr($name, 0, 2) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 2));
  1390. } else {
  1391. $name = mb_substr($name, 0, 1) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 1));
  1392. }
  1393. return $name;
  1394. }
  1395. //比如找回密码当中邮件验证码用到的
  1396. function randString($length=32)
  1397. {
  1398. return Yii::$app->getSecurity()->generateRandomString($length);
  1399. }
  1400. //生成密码
  1401. function generatePwd($password)
  1402. {
  1403. return Yii::$app->getSecurity()->generatePasswordHash($password);
  1404. }
  1405. //校验密码
  1406. function validatePwd($password,$hash)
  1407. {
  1408. return Yii::$app->getSecurity()->validatePassword($password, $hash);
  1409. }
  1410. //页面元素 name 转ID
  1411. function nameToId($name)
  1412. {
  1413. $name = str_replace('[','-',$name);
  1414. $name = str_replace(']','',$name);
  1415. return strtolower($name);
  1416. }
  1417. //抛出404
  1418. function do404()
  1419. {
  1420. throw new \Exception('页面未找到',404);
  1421. }
  1422. function isSpider() {
  1423. $agent= strtolower($_SERVER['HTTP_USER_AGENT']);
  1424. if (!empty($agent)) {
  1425. $spiderSite= array(
  1426. "TencentTraveler",
  1427. "Baiduspider+",
  1428. "BaiduGame",
  1429. "Googlebot",
  1430. "msnbot",
  1431. "Sosospider+",
  1432. "Sogou web spider",
  1433. "ia_archiver",
  1434. "Yahoo! Slurp",
  1435. "YoudaoBot",
  1436. "Yahoo Slurp",
  1437. "MSNBot",
  1438. "Java (Often spam bot)",
  1439. "BaiDuSpider",
  1440. "Voila",
  1441. "Yandex bot",
  1442. "BSpider",
  1443. "twiceler",
  1444. "Sogou Spider",
  1445. "Speedy Spider",
  1446. "Google AdSense",
  1447. "Heritrix",
  1448. "Python-urllib",
  1449. "Alexa (IA Archiver)",
  1450. "Ask",
  1451. "Exabot",
  1452. "Custo",
  1453. "OutfoxBot/YodaoBot",
  1454. "yacy",
  1455. "SurveyBot",
  1456. "legs",
  1457. "lwp-trivial",
  1458. "Nutch",
  1459. "StackRambler",
  1460. "The web archive (IA Archiver)",
  1461. "Perl tool",
  1462. "MJ12bot",
  1463. "Netcraft",
  1464. "MSIECrawler",
  1465. "WGet tools",
  1466. "larbin",
  1467. "Fish search",
  1468. );
  1469. foreach($spiderSite as $val) {
  1470. $str = strtolower($val);
  1471. if (strpos($agent, $str) !== false) {
  1472. return true;
  1473. }
  1474. }
  1475. } else {
  1476. return false;
  1477. }
  1478. }
  1479. /**
  1480. * @param array $_define 默认seo配置
  1481. * @param unknown_type $_values 对应 targets 的一组值
  1482. * @param unknown_type $_targets
  1483. * @return multitype:string
  1484. */
  1485. function seoSettings($_define = array(), $_replaceconfig = array(),$_default = array()) {
  1486. if (!empty($_define)) {
  1487. $cTitle = $_define[$_replaceconfig['pre'].'meta_title'];
  1488. $cKeywords = $_define[$_replaceconfig['pre'].'meta_keywords'];
  1489. $cDescription = $_define[$_replaceconfig['pre'].'meta_description'];
  1490. }
  1491. $_values = $_replaceconfig['values'];
  1492. $_targets = $_replaceconfig['targets'];
  1493. /* 过滤参数 */
  1494. foreach ($_values as $key => $value) {
  1495. $_values[$key] = empty($value) ? '' : trim(strip_tags($value));
  1496. }
  1497. /*设置默认值*/
  1498. empty($cTitle) && $cTitle = $_default['meta_title'];
  1499. empty($cKeywords) && $cKeywords = $_default['meta_keywords'];
  1500. empty($cDescription) && $cDescription = $_default['meta_description'];
  1501. /* 参数处理 */
  1502. $webPageTitle = parseSeoTargets($cTitle, $_values, $_targets);
  1503. $metaDescription = parseSeoTargets($cDescription, $_values, $_targets);
  1504. $metaKeywords = trim(parseSeoTargets($cKeywords, $_values, $_targets),',');
  1505. $metaKeywords = str_replace(',',',',trim($metaKeywords,','));
  1506. //如果关键词为空,用标题替代
  1507. if(empty($metaKeywords))$metaKeywords = $webPageTitle;
  1508. return array($webPageTitle, $metaKeywords, $metaDescription);
  1509. }
  1510. /**
  1511. * @param string $content
  1512. * @param array $_replace
  1513. * @param array $_targets
  1514. * @return string
  1515. */
  1516. function parseSeoTargets($content, $_values, $_targets) {
  1517. $content = str_replace($_targets, $_values, $content);
  1518. $content = trim(preg_replace(array('((\s*\,\s*)+)', '((\s*\|\s*)+)', '((\s*\t\s*)+)'), array(
  1519. ',', '|', '', ''), $content), ' -,|');
  1520. return $content;
  1521. }
  1522. //获取目录(含子目录)下所有文件
  1523. function get_allfiles($path,&$files) {
  1524. if(is_dir($path)){
  1525. $dp = dir($path);
  1526. while ($file = $dp ->read()){
  1527. if($file !="." && $file !=".."){
  1528. get_allfiles($path."/".$file, $files);
  1529. }
  1530. }
  1531. $dp ->close();
  1532. }
  1533. if(is_file($path)){
  1534. $files[] = $path;
  1535. }
  1536. }
  1537. function get_filenamesbydir($dir){
  1538. $files = array();
  1539. get_allfiles($dir,$files);
  1540. return $files;
  1541. }
  1542. ?>