global1.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  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. /*
  322. * 对用户密码进行加密,用于后台
  323. * @parame $password
  324. * @parame $encrypt //加密因子
  325. * @return string
  326. *
  327. */
  328. function password($password,$encrypt='')
  329. {
  330. $pwd = array();
  331. $pwd['encrypt'] = $encrypt?$encrypt:random(6, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
  332. $pwd['password'] = md5(md5($password).$pwd['encrypt']);
  333. return $encrypt?$pwd['password']:$pwd;
  334. }
  335. /*
  336. * 判断是否为非法输入
  337. * @parame $string
  338. * return boolean
  339. *
  340. */
  341. function is_bad_word($string)
  342. {
  343. $array = array('"','\\',' ','&','*','#','/','<','>','\r','\t','\n','#',"'");
  344. foreach($array as $value)
  345. {
  346. if(strpos($string,$value)!==false)
  347. {
  348. return true;
  349. }
  350. else
  351. {
  352. return false;
  353. }
  354. }
  355. }
  356. /*
  357. * 对数据进行编码转换
  358. * @param array/string $data 数组
  359. * @param string $input 需要转换的编码
  360. * @param string $output 转换后的编码
  361. *
  362. */
  363. function array_iconv($data,$input='gbk',$output='utf-8')
  364. {
  365. if(!is_array($data))
  366. {
  367. $data = iconv($input,$output."//IGNORE",$data);
  368. }
  369. else
  370. {
  371. foreach($data as $key=>$value)
  372. {
  373. $data[$key] = iconv($input,$output."//IGNORE",$value);
  374. }
  375. }
  376. return $data;
  377. }
  378. /**
  379. * 字符串加密、解密函数
  380. * @param string $txt 字符串
  381. * @param string $operation ENCODE为加密,DECODE为解密,可选参数,默认为ENCODE,
  382. * @param string $key 密钥:数字、字母、下划线
  383. * @param string $expiry 过期时间
  384. * @return string
  385. *
  386. */
  387. function sys_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
  388. $key_length = 4;
  389. $key = md5($key != '' ? $key : AUTH_KEY);
  390. $fixedkey = md5($key);
  391. $egiskeys = md5(substr($fixedkey, 16, 16));
  392. $runtokey = $key_length ? ($operation == 'ENCODE' ? substr(md5(microtime(true)), -$key_length) : substr($string, 0, $key_length)) : '';
  393. $keys = md5(substr($runtokey, 0, 16) . substr($fixedkey, 0, 16) . substr($runtokey, 16) . substr($fixedkey, 16));
  394. $string = $operation == 'ENCODE' ? sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$egiskeys), 0, 16) . $string : base64_decode(substr($string, $key_length));
  395. $i = 0; $result = '';
  396. $string_length = strlen($string);
  397. for ($i = 0; $i < $string_length; $i++){
  398. $result .= chr(ord($string{$i}) ^ ord($keys{$i % 32}));
  399. }
  400. if($operation == 'ENCODE') {
  401. return $runtokey . str_replace('=', '', base64_encode($result));
  402. } else {
  403. if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$egiskeys), 0, 16)) {
  404. return substr($result, 26);
  405. } else {
  406. return '';
  407. }
  408. }
  409. }
  410. // 函数返回当前 Unix 时间戳和微秒数
  411. function getmicrotime() {
  412. list($usec, $sec) = explode(" ",microtime());
  413. return ((float)$usec + (float)$sec);
  414. }
  415. /*
  416. * 取得文件扩展
  417. * @param $filename 文件名
  418. * @return 扩展名
  419. *
  420. */
  421. function fileext($filename) {
  422. return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
  423. }
  424. /**
  425. * 查询字符是否存在于某字符串
  426. *
  427. * @param $haystack 字符串
  428. * @param $needle 要查找的字符
  429. * @return bool
  430. */
  431. function str_exists($haystack, $needle)
  432. {
  433. return !(strpos($haystack, $needle) === FALSE);
  434. }
  435. //判断远程文件
  436. function check_remote_file_exists($url)
  437. {
  438. $handle = @fopen($url, 'r');
  439. if(!$handle){
  440. return false;
  441. }else{
  442. return true;
  443. }
  444. }
  445. function check_remote_file_exists1($url)
  446. {
  447. $curl = curl_init();
  448. curl_setopt($curl, CURLOPT_URL, $url);
  449. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  450. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  451. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
  452. curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
  453. // 不取回数据
  454. curl_setopt($curl, CURLOPT_NOBODY, true);
  455. // 发送请求
  456. $result = curl_exec($curl);
  457. $found = false;
  458. // 如果请求没有发送失败
  459. if ($result !== false)
  460. {
  461. // 再检查http响应码是否为200
  462. $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  463. if ($statusCode == 200)
  464. {
  465. $found = true;
  466. }
  467. }
  468. curl_close($curl);
  469. return $found;
  470. }
  471. //获取远程文件大小
  472. function remote_file_size($url)
  473. {
  474. $curl = curl_init();
  475. curl_setopt($curl, CURLOPT_URL, $url);
  476. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  477. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  478. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
  479. curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
  480. // 不取回数据
  481. curl_setopt($curl, CURLOPT_NOBODY, true);
  482. // 发送请求
  483. $result = curl_exec($curl);
  484. $size = 0;
  485. // 如果请求没有发送失败
  486. if ($result !== false)
  487. {
  488. $size = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
  489. }
  490. curl_close($curl);
  491. return $size;
  492. }
  493. /*
  494. * 判断是否为图片
  495. *
  496. */
  497. function is_image($file) {
  498. $ext_arr = array('jpg','gif','png','bmp','jpeg','tiff');
  499. $ext = fileext($file);
  500. return in_array($ext,$ext_arr) ? $ext_arr :false;
  501. }
  502. /*
  503. * 判断是否为视频
  504. *
  505. */
  506. function is_video($file) {
  507. $ext_arr = array('rm','mpg','avi','mpeg','wmv','flv','asf','rmvb');
  508. $ext = fileext($file);
  509. return in_array($ext,$ext_arr) ? $ext_arr :false;
  510. }
  511. //保存远程图片
  512. function save_remote_file($remote_url,$local_path)
  513. {
  514. $file = https_request($remote_url);
  515. file_put_contents($local_path,$file);
  516. return $local_path;
  517. }
  518. //根据路径判断是否网络文件
  519. function is_net_file($url)
  520. {
  521. if(preg_match('/^https?.*$/',$url))//网络文件
  522. {
  523. return true;
  524. }
  525. else
  526. {
  527. return false;
  528. }
  529. }
  530. /*
  531. * 检查id是否存在于数组中
  532. * @param $id
  533. * @param $ids
  534. * @param $s
  535. *
  536. */
  537. function check_in($id, $ids = '', $s = ',') {
  538. if(!$ids) return false;
  539. $ids = explode($s, $ids);
  540. return is_array($id) ? array_intersect($id, $ids) : in_array($id, $ids);
  541. }
  542. //判断目录是否可写
  543. function dir_writeable($dir) {
  544. $writeable = 0;
  545. if(is_dir($dir)) {
  546. if($fp = @fopen("$dir/chkdir.test", 'w')) {
  547. @fclose($fp);
  548. @unlink("$dir/chkdir.test");
  549. $writeable = 1;
  550. } else {
  551. $writeable = 0;
  552. }
  553. }
  554. return $writeable;
  555. }
  556. /**
  557. * 图片水印:gif,jpeg,png
  558. * @param $imgSrc
  559. * @param $markImg:水印图
  560. * @param $markPos:水印位置 0:随机位置,在1~9之间随机选取一个位置
  561. 1:顶部居左 2:顶部居中 3:顶部居右 4:左边居中
  562. 5:图片中心 6:右边居中 7:底部居左 8:底部居中 9:底部居右
  563. */
  564. function set_img_water($imgSrc,$markImg,$markQty=100,$markPos=9){
  565. if(intval($markQty)==0)$markQty=100;
  566. $srcInfo = @getimagesize($imgSrc);
  567. $srcImg_w = $srcInfo[0];
  568. $srcImg_h = $srcInfo[1];
  569. $srcim = null; $markim = null;
  570. switch ($srcInfo[2])
  571. {
  572. case 1:
  573. $srcim =imagecreatefromgif($imgSrc); break;
  574. case 2:
  575. $srcim =imagecreatefromjpeg($imgSrc); break;
  576. case 3:
  577. $srcim =imagecreatefrompng($imgSrc); break;
  578. default:
  579. die('unsupport file type'); exit();
  580. }
  581. if(!file_exists($markImg) || empty($markImg)){return;}
  582. $markImgInfo = @getimagesize($markImg);
  583. $markImg_w = $markImgInfo[0];
  584. $markImg_h = $markImgInfo[1];
  585. if($srcImg_w < $markImg_w || $srcImg_h < $markImg_h){return false;}
  586. switch ($markImgInfo[2])
  587. {
  588. case 1:
  589. $markim =imagecreatefromgif($markImg); break;
  590. case 2:
  591. $markim =imagecreatefromjpeg($markImg); break;
  592. case 3:
  593. $markim =imagecreatefrompng($markImg); break;
  594. default:
  595. return false;//die('不支持的水印图片文件类型');exit();
  596. }
  597. $logow = $markImg_w;
  598. $logoh = $markImg_h;
  599. if($markPos == 0){$markPos = rand(1, 9);}
  600. switch($markPos)
  601. {
  602. case 1: $x = +5; $y = +5; break;//顶部居左
  603. case 2: $x = ($srcImg_w-$logow)/2; $y = +5; break;//顶部居中
  604. case 3: $x = $srcImg_w- $logow-5; $y = +15; break;//顶部居右
  605. case 4: $x = +5; $y = ($srcImg_h-$logoh)/2; break;//左边居中
  606. case 5: $x = ($srcImg_w-$logow)/2; $y = ($srcImg_h-$logoh)/2; break;//图片中心
  607. case 6: $x = $srcImg_w-$logow-5; $y = ($srcImg_h-$logoh)/2; break;//右边居中
  608. case 7: $x = +5; $y = $srcImg_h-$logoh-5; break;//底部居左
  609. case 8: $x = ($srcImg_w-$logow)/2; $y = $srcImg_h-$logoh-5; break;//底部居中
  610. case 9: $x = $srcImg_w-$logow-5; $y = $srcImg_h-$logoh-5; break;//底部居右
  611. default:
  612. return false;//die('此位置不支持');exit;
  613. }
  614. $dst_img = @imagecreatetruecolor($srcImg_w, $srcImg_h);
  615. imagecopy($dst_img, $srcim, 0, 0, 0, 0, $srcImg_w, $srcImg_h);
  616. imagecopy($dst_img, $markim, $x, $y, 0, 0, $logow, $logoh);
  617. imagedestroy($markim);
  618. switch ($srcInfo[2])
  619. {
  620. case 1: imagegif($dst_img, $imgSrc); break;
  621. case 2: imagejpeg($dst_img, $imgSrc);break;
  622. case 3: imagepng($dst_img, $imgSrc); break;
  623. default: break;
  624. }
  625. imagedestroy($dst_img);
  626. imagedestroy($srcim);
  627. return true;
  628. }
  629. //获取一个唯一文件名
  630. function get_unique_file_name($path,$ext)
  631. {
  632. $fileName = TIMESTAMP.random(6, '0123456789abcdefghijklmnopqrstuvwxyz').".".$ext;//文件重命名
  633. if(!file_exists($path.$fileName))
  634. {
  635. return $fileName;
  636. }
  637. else
  638. {
  639. return get_unique_file_name($path,$ext);
  640. }
  641. }
  642. //转换数组为可适应SQL语句插入语法值集合
  643. function change_array_to_sql_string($array=array()){ //转换数组为可适应SQL语句插入语法值集合
  644. $array=str_replace("'","\'",$array);
  645. return "'".implode("','",$array)."'";
  646. }
  647. // 截取某部分字符
  648. function interception_of_string($string='',$start='',$end='')
  649. {
  650. if($string==''){return '';}
  651. if($start!='')
  652. {
  653. $pos = strpos($string,$start);
  654. if($pos===false)
  655. {
  656. return '';
  657. }
  658. else
  659. {
  660. $pos += strlen($start);
  661. $string = substr($string,$pos);
  662. }
  663. }
  664. if($end!='')
  665. {
  666. $pos = strpos($string,$end);
  667. if($pos)
  668. {
  669. $string = substr($string,0,$pos);
  670. }
  671. }
  672. return $string;
  673. }
  674. //Curl
  675. function https_request($url,$options = null,$data = null,$header = null){
  676. $curl = curl_init();
  677. curl_setopt($curl, CURLOPT_URL, $url);
  678. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  679. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  680. curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); //强制协议为1.0
  681. curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); //强制使用IPV4协议解析域名
  682. if (!empty($data)){
  683. curl_setopt($curl, CURLOPT_POST, 1);
  684. curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
  685. }
  686. (isset($options['header'])&&$options['header'])?curl_setopt($curl, CURLOPT_HEADER, 1): curl_setopt($curl, CURLOPT_HEADER, 0);//如果有响应头
  687. if(!empty($header))//如果有请求头
  688. {
  689. $curl_header = array();
  690. foreach($header as $key=>$value)
  691. {
  692. $curl_header[] = "$key:$value";
  693. }
  694. curl_setopt($curl,CURLOPT_HTTPHEADER, $curl_header);
  695. }
  696. if(isset($options['gzip'])&&$options['gzip']==1) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); //如果页面开启了GZIP压缩
  697. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  698. curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0');
  699. if(!empty($options['time_out']))
  700. {
  701. curl_setopt($curl, CURLOPT_TIMEOUT, $options['time_out']);
  702. }
  703. else
  704. {
  705. curl_setopt($curl, CURLOPT_TIMEOUT, 15);
  706. }
  707. curl_setopt ($curl, CURLOPT_REFERER, get_url());
  708. $output = curl_exec($curl);
  709. curl_close($curl);
  710. return $output;
  711. }
  712. /**批量替换敏感词
  713. * @param array $badwords 敏感词数组
  714. * @param array $replacement 替换词数组
  715. * @param string $str 待替换内容
  716. * @return string
  717. */
  718. function multi_replace($badwords,$replacement,$str)
  719. {
  720. $replaceList = array();
  721. if(is_array($badwords))
  722. {
  723. foreach($badwords as $badword)
  724. {
  725. $length = mb_strlen($badword,CHARSET);
  726. $temp='';
  727. for($i=0;$i<$length;$i++)
  728. {
  729. $temp .= $replacement;
  730. }
  731. $replaceList[] = $temp;
  732. }
  733. }
  734. return $str = str_replace($badwords,$replaceList,$str);
  735. }
  736. /**封装后的配置文件包含方法
  737. */
  738. function require_config($file)
  739. {
  740. if(defined('SITE_MODE'))
  741. {
  742. return require BASE_PATH.'config'.DIRECTORY_SEPARATOR.SITE_MODE.DIRECTORY_SEPARATOR.$file;
  743. }
  744. else
  745. {
  746. return require BASE_PATH.'config'.DIRECTORY_SEPARATOR.$file;
  747. }
  748. }
  749. //格式正则校验
  750. function pattern_check($type,$value)
  751. {
  752. switch($type)
  753. {
  754. case 'url':
  755. $pattern = '/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/';
  756. break;
  757. case 'email':
  758. $pattern = '/^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/';
  759. break;
  760. default:break;
  761. }
  762. if(!empty($pattern)&&preg_match($pattern,$value)){
  763. return true;
  764. }
  765. else{
  766. return false;
  767. }
  768. }
  769. //请求安全检测
  770. function check_safe_request_params(){
  771. $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)";
  772. $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)";
  773. $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)";
  774. $referer=empty($_SERVER['HTTP_REFERER']) ? array() : array($_SERVER['HTTP_REFERER']);
  775. foreach($_GET as $key=>$value){
  776. if (!check_request_params_ok($key,$value,$getfilter)){exit;}
  777. }
  778. foreach($_POST as $key=>$value){
  779. if (!check_request_params_ok($key,$value,$postfilter)){exit;}
  780. }
  781. foreach($_COOKIE as $key=>$value){
  782. if (!check_request_params_ok($key,$value,$cookiefilter)){exit;}
  783. }
  784. foreach($referer as $key=>$value){
  785. if (!check_request_params_ok($key,$value,$getfilter)){exit;}
  786. }
  787. }
  788. //请求安全检测:子方法
  789. function check_request_params_ok($StrFiltKey,$StrFiltValue,$ArrFiltReq){
  790. $StrFiltValue=arr_foreach($StrFiltValue);
  791. if (preg_match('/'.$ArrFiltReq.'/is',$StrFiltValue)==1 || preg_match('/'.$ArrFiltReq.'/is',$StrFiltKey)==1){return false;}
  792. return true;
  793. }
  794. function arr_foreach($arr) {
  795. static $str;
  796. if (!is_array($arr)) {return $arr;}
  797. foreach ($arr as $key => $val ) {
  798. if (is_array($val)) {arr_foreach($val);} else {$str[] = $val;}
  799. }
  800. return implode($str);
  801. }
  802. //带超时时间设置的file_get_contents
  803. function new_file_get_contents($url,$timeout=null)
  804. {
  805. if(isset($timeout))
  806. {
  807. $opts = array(
  808. 'http'=>array(
  809. 'method'=>"GET",
  810. 'timeout'=>$timeout,//单位秒
  811. )
  812. );
  813. return file_get_contents( $url, false, stream_context_create($opts));
  814. }
  815. else
  816. {
  817. return file_get_contents($url);
  818. }
  819. }
  820. //判断是否蜘蛛请求
  821. function checkrobot($useragent = '') {
  822. static $kw_spiders = array('bot', 'crawl', 'spider' ,'slurp', 'sohu-search', 'lycos', 'robozilla','haosouspider','baidu','sogou','yisouspider','360spider','baiduspide','soso','yahoo','bingbot');
  823. static $kw_browsers = array('msie', 'netscape', 'opera', 'konqueror', 'mozilla');
  824. $useragent = strtolower(empty($useragent) ? $_SERVER['HTTP_USER_AGENT'] : $useragent);
  825. if(strpos($useragent, 'http://') === false && dstrpos($useragent, $kw_browsers)) return false;
  826. if(dstrpos($useragent, $kw_spiders)) return true;
  827. return false;
  828. }
  829. function dstrpos($string, &$arr, $returnvalue = false) {
  830. if(empty($string)) return false;
  831. foreach((array)$arr as $v) {
  832. if(strpos($string, $v) !== false) {
  833. $return = $returnvalue ? $v : true;
  834. return $return;
  835. }
  836. }
  837. return false;
  838. }
  839. //压缩html
  840. function compress_html($str){
  841. $str = trim($str);
  842. $str = str_replace("\t","",$str);
  843. $str = str_replace("\r\n","",$str);
  844. $str = str_replace("\r","",$str);
  845. $str = str_replace("\n","",$str);
  846. $str=preg_replace("/>[ ]+/si",">",$str); //过滤>(">"号后面带空格)
  847. $str=preg_replace("/[ ]+</si","<",$str); //过滤<("<"号前面带空格)
  848. return trim($str);
  849. }
  850. //字符串过滤,只保留汉字数字英文标点符号
  851. function removeHtml($html,$filter=1)
  852. {
  853. $html = htmlspecialchars_decode($html); //把一些预定义的 HTML 实体转换为字符
  854. $html = strip_tags($html); //函数剥去字符串中的 HTML、XML 以及 PHP 的标签,获取纯文本内容
  855. $html = trim($html); //清除字符串两边的空格
  856. $html = str_replace("&nbsp;","",$html);
  857. $html = preg_replace("/\t/","",$html); //使用正则表达式替换内容,如:空格,换行,并将替换为空。
  858. $html = preg_replace("/\r\n/","",$html);
  859. $html = preg_replace("/\r/","",$html);
  860. $html = preg_replace("/\n/","",$html);
  861. $html = preg_replace("/ /","",$html);
  862. $html = preg_replace("/ /","",$html); //匹配html中的空格
  863. $html = preg_replace('/($s*$)|(^s*^)/m', '',$html);
  864. if($filter)
  865. {
  866. preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()]/u', $html, $result);
  867. return implode('', $result[0]);
  868. }
  869. else
  870. {
  871. return $html;
  872. }
  873. }
  874. //对转换过程中获取的内容做初始处理
  875. function beforeProcessHtml($html)
  876. {
  877. preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u', $html, $testResult);
  878. if(empty($testResult[0]))
  879. {
  880. $html = mb_convert_encoding($html, 'UTF-8', 'UTF-8');
  881. preg_match_all('/[\x{4e00}-\x{9fa5}a-zA-Z0-9。、!?:;﹑•"…‘’“”〝〞∕¦‖— 〈〉﹞﹝「」‹›〖〗】【»«』『〕〔》《﹐¸﹕︰﹔!¡?¿﹖﹌﹏﹋'´ˊˋ―﹫︳︴¯_ ̄﹢﹦﹤‐­˜﹟﹩﹠﹪﹡﹨﹍﹉﹎﹊ˇ︵︶︷︸︹︿﹀︺︽︾ˉ﹁﹂﹃﹄︻︼()]/u', $html, $result);
  882. return implode('', $result[0]);
  883. }
  884. else
  885. {
  886. return $html;
  887. }
  888. }
  889. //获取所有的cookie内容
  890. function get_all_cookie_str(){
  891. $ckeStr='';
  892. foreach ($_COOKIE as $ckeName=>$ckeVal){
  893. if(!is_array($ckeVal)){
  894. $ckeStr.= $ckeName.'='.$ckeVal.';';
  895. }
  896. }
  897. $ckeStr = substr($ckeStr, 0,-1);//去除最后的 ;
  898. return $ckeStr;
  899. }
  900. //PHP默认serialize有时会出错 http://us.php.net/manual/en/function.unserialize.php#71270
  901. function mb_unserialize($serial_str) {
  902. $serial_str= preg_replace('!s:(\d+):"(.*?)";!se', "'s:'.strlen('$2').':\"$2\";'", $serial_str );
  903. $serial_str= str_replace("\r", "", $serial_str);
  904. return unserialize($serial_str);
  905. }
  906. //判断是否是移动端访问
  907. function check_mobile($debug = false) {
  908. static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
  909. 'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
  910. 'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
  911. 'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
  912. 'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
  913. 'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
  914. 'benq', 'haier', '^lct', '320x320', '240x320', '176x220');
  915. static $mobilebrowser_list =array('windows phone');
  916. static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
  917. 'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
  918. 'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
  919. $pad_list = array('pad', 'gt-p1000');
  920. $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
  921. if(($v = dstrpos($useragent, $mobilebrowser_list, true))){
  922. return '1'; //windows phone
  923. }
  924. if(($v = dstrpos($useragent, $touchbrowser_list, true))){
  925. return '2';
  926. }
  927. if(($v = dstrpos($useragent, $wmlbrowser_list))) {
  928. return '3'; //wml版
  929. }
  930. $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
  931. if(dstrpos($useragent, $brower)) return false;
  932. return false;
  933. }
  934. //时间换算
  935. function info_last_time($time,$ac="Y年m月d日") {
  936. $now=TIMESTAMP-$time;
  937. $timestr = (substr_count($ac,'-')>0?'Y-m-d':'Y年m月d日');
  938. if ($now>3456000) return get_date($time,$timestr);
  939. elseif ($now>345600) return get_date($time,$ac);
  940. elseif ($now>259200) return "三天前";
  941. elseif ($now>172800) return "两天前";
  942. elseif ($now>86400) return "一天前";
  943. elseif ($now>72000) return "二十小时前";
  944. elseif ($now>54000) return "十五小时前";
  945. elseif ($now>43200) return "十二小时前";
  946. elseif ($now>36000) return "十小时前";
  947. elseif ($now>28800) return "八小时前";
  948. elseif ($now>21600) return "六小时前";
  949. elseif ($now>18000) return "五小时前";
  950. elseif ($now>10800) return "三小时前";
  951. elseif ($now>7200) return "两小时前";
  952. elseif ($now>3600) return "一小时前";
  953. elseif ($now>1800) return "半小时前";
  954. elseif ($now>1200) return "二十分钟前";
  955. elseif ($now>900) return "十五分钟前";
  956. elseif ($now>600) return "十分钟前";
  957. elseif ($now>300) return "五分钟前";
  958. elseif ($now>180) return "三分钟前";
  959. elseif ($now>120) return "两分钟前";
  960. elseif ($now>=0) return "一分钟前";
  961. elseif ($now<0) return "一秒钟前";
  962. return get_date($time,$ac);
  963. }
  964. /**
  965. * 格式化时间戳为日期字符串
  966. * @global string $db_datefm
  967. * @global string $db_timedf
  968. * @global string $_datefm
  969. * @global string $_timedf
  970. * @param int $timestamp
  971. * @param string $format
  972. * @return string
  973. */
  974. function get_date($timestamp, $format = null) {
  975. if(empty($timestamp))return '';
  976. $obj = new \DateTime("@$timestamp"); // 这里时间戳前要写一个@符号
  977. $timezone = timezone_open(TIME_ZONE); // 设置时区
  978. $obj->setTimezone($timezone);
  979. $sDefaultFormat = $format ? $format : 'Y-m-d H:i';
  980. return $obj->format($sDefaultFormat);
  981. }
  982. //日期转时间戳
  983. function str_to_time($str)
  984. {
  985. $date = new \DateTime($str);
  986. return $date->format('U');
  987. }
  988. //301跳转
  989. function header_goto($str) {
  990. Header("HTTP/1.1 301 Moved Permanently");
  991. Header($str);exit;
  992. }
  993. /**
  994. * 截断字符串
  995. *
  996. * @param string $content 内容
  997. * @param int $length 截取字节数
  998. * @param string $add 是否带省略号,Y|N
  999. * @return string
  1000. */
  1001. function substrs($content, $length, $add = 'Y') {
  1002. if (strlen($content) > $length) {
  1003. if (CHARSET != 'utf-8') {
  1004. $cutStr = '';
  1005. for ($i = 0; $i < $length - 1; $i++) {
  1006. $cutStr .= ord($content[$i]) > 127 ? $content[$i] . $content[++$i] : $content[$i];
  1007. }
  1008. $i < $length && ord($content[$i]) <= 127 && $cutStr .= $content[$i];
  1009. return $cutStr . ($add == 'Y' ? ' ..' : '');
  1010. }
  1011. return utf8_trim(substr($content, 0, $length)) . ($add == 'Y' ? ' ..' : '');
  1012. }
  1013. return $content;
  1014. }
  1015. /**
  1016. * utf8字符串整齐化
  1017. *
  1018. * @param string $str
  1019. * @return string
  1020. */
  1021. function utf8_trim($str) {
  1022. $hex = '';
  1023. $len = strlen($str) - 1;
  1024. for ($i = $len; $i >= 0; $i -= 1) {
  1025. $ch = ord($str[$i]);
  1026. $hex .= " $ch";
  1027. if (($ch & 128) == 0 || ($ch & 192) == 192) {return substr($str, 0, $i);}
  1028. }
  1029. return $str . $hex;
  1030. }
  1031. function echo_json($arr){
  1032. ob_clean();
  1033. header('Content-type: application/json');
  1034. echo json_encode($arr);exit;
  1035. }
  1036. //生成唯一订单号
  1037. function getUniOrderNo()
  1038. {
  1039. $order_id = get_date(TIMESTAMP,'Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  1040. $exists = \app\modules\shopping\models\ShoppingOrder::find()->where("order_sn='".$order_id."'")->exists();
  1041. if($exists)
  1042. {
  1043. return getUniOrderNo();
  1044. }
  1045. else
  1046. {
  1047. return $order_id;
  1048. }
  1049. }
  1050. //生成唯一券号
  1051. function getUniCouponNo()
  1052. {
  1053. $coupon_no = get_date(TIMESTAMP,'Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
  1054. $exists = \app\modules\ucenter\models\UserVipCoupon::find()->where("coupon_no='".$coupon_no."'")->exists();
  1055. if($exists)
  1056. {
  1057. return getUniCouponNo();
  1058. }
  1059. else
  1060. {
  1061. return $coupon_no;
  1062. }
  1063. }
  1064. //生成唯一订单号(毫秒级)
  1065. function getProUniOrderNo()
  1066. {
  1067. $order_id_main = get_date(TIMESTAMP,'YmdHis') . rand(10,99);
  1068. $order_id_len = strlen($order_id_main);
  1069. $order_id_sum = 0;
  1070. for($i=0; $i<$order_id_len; $i++){
  1071. $order_id_sum += (int)(substr($order_id_main,$i,1));
  1072. }
  1073. $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
  1074. return $order_id;
  1075. }
  1076. /**
  1077. * 二維数组排序
  1078. */
  1079. function array_sort($arr,$sort)
  1080. {
  1081. /* $sort = array(
  1082. 'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序;SORT_ASC 升序
  1083. 'field' => 'length', //排序字段
  1084. );*/
  1085. $arrSort = array();
  1086. foreach($arr AS $uniqid => $row){
  1087. foreach($row AS $key=>$value){
  1088. $arrSort[$key][$uniqid] = $value;
  1089. }
  1090. }
  1091. if($sort['direction']){
  1092. array_multisort($arrSort[$sort['field']], constant($sort['direction']), $arr);
  1093. }
  1094. return $arr;
  1095. }
  1096. /**
  1097. * 可以统计中文字符串长度的函数
  1098. * @param $str 要计算长度的字符串
  1099. * @param $type 计算长度类型,0(默认)表示一个中文算一个字符,1表示一个中文算两个字符
  1100. */
  1101. function abslength($str)
  1102. {
  1103. if(empty($str)){
  1104. return 0;
  1105. }
  1106. if(function_exists('mb_strlen')){
  1107. return mb_strlen($str,'utf-8');
  1108. }
  1109. else {
  1110. preg_match_all("/./u", $str, $ar);
  1111. return count($ar[0]);
  1112. }
  1113. }
  1114. //过滤微信表情
  1115. function filterEmoji($nickname)
  1116. {
  1117. $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickname);
  1118. $nickname = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nickname);
  1119. $nickname = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nickname);
  1120. $nickname = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nickname);
  1121. $nickname = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nickname);
  1122. $nickname = str_replace(array('"','\''), '', $nickname);
  1123. return $nickname;
  1124. }
  1125. //单条对象记录转数组
  1126. function single_object_to_array($result,$needfield = array())
  1127. {
  1128. $info = array();
  1129. if(is_object($result))
  1130. {
  1131. foreach($result as $key=>$value)
  1132. {
  1133. if(!empty($needfield)&&in_array($key,$needfield))
  1134. {
  1135. $info[$key] = $value;
  1136. }
  1137. if(empty($needfield))
  1138. {
  1139. $info[$key] = $value;
  1140. }
  1141. }
  1142. return $info;
  1143. }
  1144. else
  1145. {
  1146. return $result;
  1147. }
  1148. }
  1149. //获得文件绝对路径
  1150. function getFileUrl($path,$internal=0)
  1151. {
  1152. if(empty($path)) return;
  1153. if(strpos($path,'http')!==false)
  1154. {
  1155. $path = str_replace(array('https://','http://'),array(SITE_PROTOCOL,SITE_PROTOCOL),$path);
  1156. }
  1157. else
  1158. {
  1159. //如果开启了OSS
  1160. if(Yii::$app->params['oss']['OPEN_OSS'])
  1161. {
  1162. if($internal==1)
  1163. {
  1164. $path = getOssInterUrl().$path;
  1165. }
  1166. else
  1167. {
  1168. $path = getOssUrl().$path;
  1169. }
  1170. }
  1171. else
  1172. {
  1173. $path = UPLOAD_URL.$path;
  1174. }
  1175. }
  1176. if(IN_WAP)
  1177. {
  1178. $path = str_replace(WEB_URL,WAP_URL,$path);
  1179. }
  1180. return $path;
  1181. }
  1182. //获得文件转换结果路径
  1183. function getFileWorkPath($file)
  1184. {
  1185. $result = parse_url($file);
  1186. $path= str_replace('/upload/','',$result['path']);
  1187. $ext = fileext($path);
  1188. $workpath = dirname($path).DIRECTORY_SEPARATOR.md5(basename($path,'.'.$ext)).DIRECTORY_SEPARATOR;
  1189. $workpath = ltrim(str_replace(DIRECTORY_SEPARATOR,'/',$workpath),'/');
  1190. return $workpath;
  1191. }
  1192. //获得文件相对路径
  1193. function getFilePath($file)
  1194. {
  1195. $result = parse_url($file);
  1196. $path= str_replace('/upload/','',$result['path']);
  1197. return $path;
  1198. }
  1199. function unserializeFileRealUrl($string,$first=true)
  1200. {
  1201. $fileList = string2array($string);
  1202. $urls = '';
  1203. if($first)
  1204. {
  1205. if(isset($fileList['filepath']))
  1206. {
  1207. if(!empty($fileList['filepath']))
  1208. {
  1209. $urls = getFileUrl($fileList['filepath']);
  1210. }
  1211. }
  1212. else
  1213. {
  1214. if(!empty($fileList[0]['filepath']))
  1215. {
  1216. if(strpos($fileList[0]['fileurl'],'http')!==false)
  1217. {
  1218. return $fileList[0]['fileurl'];
  1219. }
  1220. else
  1221. {
  1222. $urls = getFileUrl($fileList[0]['filepath']);
  1223. }
  1224. }
  1225. }
  1226. }
  1227. else
  1228. {
  1229. $urls = array();
  1230. if(is_array($fileList))foreach($fileList as $file)
  1231. {
  1232. if(!empty($file['filepath']))$urls[] = getFileUrl($file['filepath']);
  1233. }
  1234. }
  1235. return $urls;
  1236. }
  1237. //判断是否是手机站
  1238. function is_wap_site()
  1239. {
  1240. if(IN_WAP==true)
  1241. {
  1242. return true;
  1243. }
  1244. else
  1245. {
  1246. return false;
  1247. }
  1248. }
  1249. //判断是IOS或安卓系统
  1250. function get_device_type()
  1251. {
  1252. //全部变成小写字母
  1253. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1254. $type ='other';
  1255. //分别进行判断
  1256. if(strpos($agent,'iphone') || strpos($agent,'ipad'))
  1257. {
  1258. $type ='ios';
  1259. }
  1260. if(strpos($agent,'android'))
  1261. {
  1262. $type ='android';
  1263. }
  1264. return $type;
  1265. }
  1266. //判断是否是微信访问
  1267. function check_micromsg()
  1268. {
  1269. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1270. if (stripos($agent, 'MicroMessenger') !== false)
  1271. {
  1272. return true;
  1273. } else {
  1274. return false;
  1275. }
  1276. }
  1277. //判断是否是百度小程序访问
  1278. function check_baiduapp()
  1279. {
  1280. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1281. if (stripos($agent, 'baiduboxapp') !== false)
  1282. {
  1283. return true;
  1284. } else {
  1285. return false;
  1286. }
  1287. }
  1288. //判断是否是微信小程序访问
  1289. function check_wxapp()
  1290. {
  1291. $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
  1292. if (stripos($agent, 'miniprogram') !== false)
  1293. {
  1294. return true;
  1295. } else {
  1296. return false;
  1297. }
  1298. }
  1299. /*
  1300. * 作用:用*号替代姓名除第一个字之外的字符
  1301. * 参数:
  1302. *
  1303. *
  1304. * 返回值:string
  1305. */
  1306. function starReplace($name, $num = 0)
  1307. {
  1308. if ($num && mb_strlen($name, 'UTF-8') > $num) {
  1309. return mb_substr($name, 0, 4) . '*';
  1310. }
  1311. if ($num && mb_strlen($name, 'UTF-8') <= $num) {
  1312. return $name;
  1313. }
  1314. $doubleSurname = [
  1315. '欧阳', '太史', '端木', '上官', '司马', '东方', '独孤', '南宫',
  1316. '万俟', '闻人', '夏侯', '诸葛', '尉迟', '公羊', '赫连', '澹台', '皇甫', '宗政', '濮阳',
  1317. '公冶', '太叔', '申屠', '公孙', '慕容', '仲孙', '钟离', '长孙', '宇文', '司徒', '鲜于',
  1318. '司空', '闾丘', '子车', '亓官', '司寇', '巫马', '公西', '颛孙', '壤驷', '公良', '漆雕', '乐正',
  1319. '宰父', '谷梁', '拓跋', '夹谷', '轩辕', '令狐', '段干', '百里', '呼延', '东郭', '南门', '羊舌',
  1320. '微生', '公户', '公玉', '公仪', '梁丘', '公仲', '公上', '公门', '公山', '公坚', '左丘', '公伯',
  1321. '西门', '公祖', '第五', '公乘', '贯丘', '公皙', '南荣', '东里', '东宫', '仲长', '子书', '子桑',
  1322. '即墨', '达奚', '褚师', '吴铭'
  1323. ];
  1324. $surname = mb_substr($name, 0, 2);
  1325. if (in_array($surname, $doubleSurname)) {
  1326. $name = mb_substr($name, 0, 2) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 2));
  1327. } else {
  1328. $name = mb_substr($name, 0, 1) . str_repeat('*', (mb_strlen($name, 'UTF-8') - 1));
  1329. }
  1330. return $name;
  1331. }
  1332. //比如找回密码当中邮件验证码用到的
  1333. function randString($length=32)
  1334. {
  1335. return Yii::$app->getSecurity()->generateRandomString($length);
  1336. }
  1337. //生成密码
  1338. function generatePwd($password)
  1339. {
  1340. return Yii::$app->getSecurity()->generatePasswordHash($password);
  1341. }
  1342. //校验密码
  1343. function validatePwd($password,$hash)
  1344. {
  1345. return Yii::$app->getSecurity()->validatePassword($password, $hash);
  1346. }
  1347. //页面元素 name 转ID
  1348. function nameToId($name)
  1349. {
  1350. $name = str_replace('[','-',$name);
  1351. $name = str_replace(']','',$name);
  1352. return strtolower($name);
  1353. }
  1354. //抛出404
  1355. function do404()
  1356. {
  1357. throw new \Exception('页面未找到',404);
  1358. }
  1359. function isSpider() {
  1360. $agent= strtolower($_SERVER['HTTP_USER_AGENT']);
  1361. if (!empty($agent)) {
  1362. $spiderSite= array(
  1363. "TencentTraveler",
  1364. "Baiduspider+",
  1365. "BaiduGame",
  1366. "Googlebot",
  1367. "msnbot",
  1368. "Sosospider+",
  1369. "Sogou web spider",
  1370. "ia_archiver",
  1371. "Yahoo! Slurp",
  1372. "YoudaoBot",
  1373. "Yahoo Slurp",
  1374. "MSNBot",
  1375. "Java (Often spam bot)",
  1376. "BaiDuSpider",
  1377. "Voila",
  1378. "Yandex bot",
  1379. "BSpider",
  1380. "twiceler",
  1381. "Sogou Spider",
  1382. "Speedy Spider",
  1383. "Google AdSense",
  1384. "Heritrix",
  1385. "Python-urllib",
  1386. "Alexa (IA Archiver)",
  1387. "Ask",
  1388. "Exabot",
  1389. "Custo",
  1390. "OutfoxBot/YodaoBot",
  1391. "yacy",
  1392. "SurveyBot",
  1393. "legs",
  1394. "lwp-trivial",
  1395. "Nutch",
  1396. "StackRambler",
  1397. "The web archive (IA Archiver)",
  1398. "Perl tool",
  1399. "MJ12bot",
  1400. "Netcraft",
  1401. "MSIECrawler",
  1402. "WGet tools",
  1403. "larbin",
  1404. "Fish search",
  1405. );
  1406. foreach($spiderSite as $val) {
  1407. $str = strtolower($val);
  1408. if (strpos($agent, $str) !== false) {
  1409. return true;
  1410. }
  1411. }
  1412. } else {
  1413. return false;
  1414. }
  1415. }
  1416. /**
  1417. * @param array $_define 默认seo配置
  1418. * @param unknown_type $_values 对应 targets 的一组值
  1419. * @param unknown_type $_targets
  1420. * @return multitype:string
  1421. */
  1422. function seoSettings($_define = array(), $_replaceconfig = array(),$_default = array()) {
  1423. if (!empty($_define)) {
  1424. $cTitle = $_define[$_replaceconfig['pre'].'meta_title'];
  1425. $cKeywords = $_define[$_replaceconfig['pre'].'meta_keywords'];
  1426. $cDescription = $_define[$_replaceconfig['pre'].'meta_description'];
  1427. }
  1428. $_values = $_replaceconfig['values'];
  1429. $_targets = $_replaceconfig['targets'];
  1430. /* 过滤参数 */
  1431. foreach ($_values as $key => $value) {
  1432. $_values[$key] = empty($value) ? '' : trim(strip_tags($value));
  1433. }
  1434. /*设置默认值*/
  1435. empty($cTitle) && $cTitle = $_default['meta_title'];
  1436. empty($cKeywords) && $cKeywords = $_default['meta_keywords'];
  1437. empty($cDescription) && $cDescription = $_default['meta_description'];
  1438. /* 参数处理 */
  1439. $webPageTitle = parseSeoTargets($cTitle, $_values, $_targets);
  1440. $metaDescription = parseSeoTargets($cDescription, $_values, $_targets);
  1441. $metaKeywords = trim(parseSeoTargets($cKeywords, $_values, $_targets),',');
  1442. $metaKeywords = str_replace(',',',',trim($metaKeywords,','));
  1443. //如果关键词为空,用标题替代
  1444. if(empty($metaKeywords))$metaKeywords = $webPageTitle;
  1445. return array($webPageTitle, $metaKeywords, $metaDescription);
  1446. }
  1447. /**
  1448. * @param string $content
  1449. * @param array $_replace
  1450. * @param array $_targets
  1451. * @return string
  1452. */
  1453. function parseSeoTargets($content, $_values, $_targets) {
  1454. $content = str_replace($_targets, $_values, $content);
  1455. $content = trim(preg_replace(array('((\s*\,\s*)+)', '((\s*\|\s*)+)', '((\s*\t\s*)+)'), array(
  1456. ',', '|', '', ''), $content), ' -,|');
  1457. return $content;
  1458. }
  1459. //获取目录(含子目录)下所有文件
  1460. function get_allfiles($path,&$files) {
  1461. if(is_dir($path)){
  1462. $dp = dir($path);
  1463. while ($file = $dp ->read()){
  1464. if($file !="." && $file !=".."){
  1465. get_allfiles($path."/".$file, $files);
  1466. }
  1467. }
  1468. $dp ->close();
  1469. }
  1470. if(is_file($path)){
  1471. $files[] = $path;
  1472. }
  1473. }
  1474. function get_filenamesbydir($dir){
  1475. $files = array();
  1476. get_allfiles($dir,$files);
  1477. return $files;
  1478. }
  1479. ?>