common.class.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. <?php
  2. defined('IS_INITPHP') || die('Access Denied!');
  3. /**
  4. * 扩展类库
  5. *
  6. * @version 0.1.0
  7. * @author clh
  8. */
  9. class commonClass{
  10. /**
  11. *生成时间戳
  12. * @return string
  13. */
  14. function timestamp() {
  15. list($s1, $s2) = explode(' ', microtime());
  16. return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)));
  17. }
  18. /**
  19. * 生成时间
  20. * @return string
  21. */
  22. function timenow() {
  23. return date("Y-m-d H:i:s", time());
  24. }
  25. /**
  26. * 生成时间
  27. * @return string
  28. */
  29. function datenow() {
  30. return date("Y-m-d", time());
  31. }
  32. /**
  33. * 生成时间
  34. * @return string
  35. */
  36. function datemore() {
  37. return date("Y-m-d", strtotime("+6 day"));
  38. }
  39. /**
  40. * 生成时间戳大于 多少分钟,30分种有效期
  41. * @param $timestamp 时戳
  42. * @return string
  43. */
  44. function timestampeq($timestamp=0) {
  45. list($s1, $s2) = explode(' ', microtime());
  46. return (float) floatval($timestamp)+ (floatval(60*3000));
  47. }
  48. /**
  49. * 用户token
  50. * @param $uid 用户ID
  51. * @param $timestamp 时戳
  52. * @return string
  53. */
  54. function token($uid=0,$timestamp=0) {
  55. return md5($uid.$timestamp);
  56. }
  57. /**
  58. *生成时间戳+随机码 唯一订单ID号
  59. * @return string
  60. */
  61. function orderId() {
  62. list($s1, $s2) = explode(' ', microtime());
  63. return (float)sprintf('%.0f', (floatval($s1) + floatval($s2))).$this->randomnum();
  64. }
  65. /**
  66. * 获取地址错误
  67. */
  68. function urlErr(){
  69. //jsonp回调参数,必需
  70. $callback = isset($_GET['callback']) ? trim($_GET['callback']) : '';
  71. $jsonData["dataToken"]["timestamp"]="";
  72. $jsonData["dataToken"]["token"]="";
  73. $jsonData["dataToken"]["id"]="";
  74. $jsonData["dataToken"]["status"]=0;
  75. $jsonData["dataToken"]["info"]="验证失败";
  76. $jsonData["dataInfo"]["status"]="0";
  77. $jsonData["dataInfo"]["info"]="非法访问";
  78. $jsonData["dataInfo"]["data"]="";
  79. //返回格式,有回调或没有回调两种方式
  80. if($callback){
  81. echo $callback . '(' .json_encode($jsonData) .')'; //返回格式,回调来jsonp 必需 json 数据
  82. }else{
  83. echo json_encode($jsonData); //返回格式,必需 json 数据
  84. }
  85. }
  86. function array_multi2single($array)
  87. {
  88. static $result_array=array();
  89. foreach($array as $key=>$value)
  90. {
  91. if(is_array($value))
  92. {
  93. $this->array_multi2single($value);
  94. }
  95. else
  96. $result_array[]=$value;
  97. }
  98. return $result_array;
  99. }
  100. /**
  101. * 将多维数组转为一维数组
  102. * @author echo
  103. * @param array $arr
  104. * @return array
  105. */
  106. function ArrMd2Ud($arr) {
  107. #将数值第一元素作为容器,作地址赋值。
  108. $ar_room = &$arr[key($arr)];
  109. #第一容器不是数组进去转呀
  110. if (!is_array($ar_room)) {
  111. #转为成数组
  112. $ar_room = array($ar_room);
  113. }
  114. #指针下移
  115. next($arr);
  116. #遍历
  117. while (list($k, $v) = each($arr)) {
  118. #是数组就递归深挖,不是就转成数组
  119. $v = is_array($v) ? call_user_func(__FUNCTION__, $v) : array($v);
  120. #递归合并
  121. $ar_room = array_merge_recursive($ar_room, $v);
  122. #释放当前下标的数组元素
  123. unset($arr[$k]);
  124. }
  125. return $ar_room;
  126. }
  127. /**
  128. * 获取客户端IP地址
  129. * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
  130. * @param boolean $adv 是否进行高级模式获取(有可能被伪装)
  131. * @return mixed
  132. */
  133. function ip($type = 0,$adv=false) {
  134. $type = $type ? 1 : 0;
  135. static $ip = NULL;
  136. if ($ip !== NULL) return $ip[$type];
  137. if($adv){
  138. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  139. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  140. $pos = array_search('unknown',$arr);
  141. if(false !== $pos) unset($arr[$pos]);
  142. $ip = trim($arr[0]);
  143. }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  144. $ip = $_SERVER['HTTP_CLIENT_IP'];
  145. }elseif (isset($_SERVER['REMOTE_ADDR'])) {
  146. $ip = $_SERVER['REMOTE_ADDR'];
  147. }
  148. }elseif (isset($_SERVER['REMOTE_ADDR'])) {
  149. $ip = $_SERVER['REMOTE_ADDR'];
  150. }
  151. // IP地址合法验证
  152. $long = sprintf("%u",ip2long($ip));
  153. $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
  154. return $ip[$type];
  155. }
  156. //用php从身份证中提取生日,包括15位和18位身份证
  157. function getIDCardInfo($IDCard){
  158. $result['error']=0;//0:未知错误,1:身份证格式错误,2:无错误
  159. $result['flag']='';//0标示成年,1标示未成年
  160. $result['tdate']='';//生日,格式如:2012-11-15
  161. if(!eregi("^[1-9]([0-9a-zA-Z]{17}|[0-9a-zA-Z]{14})$",$IDCard)){
  162. $result['error']=1;
  163. return $result;
  164. }else{
  165. if(strlen($IDCard)==18){
  166. $tyear=intval(substr($IDCard,6,4));
  167. $tmonth=intval(substr($IDCard,10,2));
  168. $tday=intval(substr($IDCard,12,2));
  169. if($tyear>date("Y")||$tyear<(date("Y")-100)){
  170. $flag=0;
  171. }elseif($tmonth<0||$tmonth>12){
  172. $flag=0;
  173. }elseif($tday<0||$tday>31){
  174. $flag=0;
  175. }else{
  176. $tdate=$tyear."-".$tmonth."-".$tday."";
  177. if((time()-mktime(0,0,0,$tmonth,$tday,$tyear))>18*365*24*60*60){
  178. $flag=0;
  179. }else{
  180. $flag=1;
  181. }
  182. }
  183. }elseif(strlen($IDCard)==15){
  184. $tyear=intval("19".substr($IDCard,6,2));
  185. $tmonth=intval(substr($IDCard,8,2));
  186. $tday=intval(substr($IDCard,10,2));
  187. if($tyear>date("Y")||$tyear<(date("Y")-100)){
  188. $flag=0;
  189. }elseif($tmonth<0||$tmonth>12){
  190. $flag=0;
  191. }elseif($tday<0||$tday>31){
  192. $flag=0;
  193. }else{
  194. $tdate=$tyear."-".$tmonth."-".$tday."";
  195. if((time()-mktime(0,0,0,$tmonth,$tday,$tyear))>18*365*24*60*60){
  196. $flag=0;
  197. }else{
  198. $flag=1;
  199. }
  200. }
  201. }
  202. }
  203. $result['error']=2;//0:未知错误,1:身份证格式错误,2:无错误
  204. $result['isAdult']=$flag;//0标示成年,1标示未成年
  205. $result['birthday']=$tdate;//生日日期
  206. return $result;
  207. }
  208. /**
  209. * 发送HTTP状态
  210. * @param integer $code 状态码
  211. * @return void
  212. */
  213. function send_http_status($code) {
  214. static $_status = array(
  215. // Informational 1xx
  216. 100 => 'Continue',
  217. 101 => 'Switching Protocols',
  218. // Success 2xx
  219. 200 => 'OK',
  220. 201 => 'Created',
  221. 202 => 'Accepted',
  222. 203 => 'Non-Authoritative Information',
  223. 204 => 'No Content',
  224. 205 => 'Reset Content',
  225. 206 => 'Partial Content',
  226. // Redirection 3xx
  227. 300 => 'Multiple Choices',
  228. 301 => 'Moved Permanently',
  229. 302 => 'Moved Temporarily ', // 1.1
  230. 303 => 'See Other',
  231. 304 => 'Not Modified',
  232. 305 => 'Use Proxy',
  233. // 306 is deprecated but reserved
  234. 307 => 'Temporary Redirect',
  235. // Client Error 4xx
  236. 400 => 'Bad Request',
  237. 401 => 'Unauthorized',
  238. 402 => 'Payment Required',
  239. 403 => 'Forbidden',
  240. 404 => 'Not Found',
  241. 405 => 'Method Not Allowed',
  242. 406 => 'Not Acceptable',
  243. 407 => 'Proxy Authentication Required',
  244. 408 => 'Request Timeout',
  245. 409 => 'Conflict',
  246. 410 => 'Gone',
  247. 411 => 'Length Required',
  248. 412 => 'Precondition Failed',
  249. 413 => 'Request Entity Too Large',
  250. 414 => 'Request-URI Too Long',
  251. 415 => 'Unsupported Media Type',
  252. 416 => 'Requested Range Not Satisfiable',
  253. 417 => 'Expectation Failed',
  254. // Server Error 5xx
  255. 500 => 'Internal Server Error',
  256. 501 => 'Not Implemented',
  257. 502 => 'Bad Gateway',
  258. 503 => 'Service Unavailable',
  259. 504 => 'Gateway Timeout',
  260. 505 => 'HTTP Version Not Supported',
  261. 509 => 'Bandwidth Limit Exceeded'
  262. );
  263. if(isset($_status[$code])) {
  264. header('HTTP/1.1 '.$code.' '.$_status[$code]);
  265. // 确保FastCGI模式下正常
  266. header('Status:'.$code.' '.$_status[$code]);
  267. }
  268. }
  269. function think_filter(&$value){
  270. // TODO 其他安全过滤
  271. // 过滤查询特殊字符
  272. if(preg_match('/^(EXP|NEQ|GT|EGT|LT|ELT|OR|XOR|LIKE|NOTLIKE|NOT BETWEEN|NOTBETWEEN|BETWEEN|NOTIN|NOT IN|IN)$/i',$value)){
  273. $value .= ' ';
  274. }
  275. }
  276. // 不区分大小写的in_array实现
  277. function in_array_case($value,$array){
  278. return in_array(strtolower($value),array_map('strtolower',$array));
  279. }
  280. /**
  281. * 对用户的密码进行加密
  282. * @param $password
  283. * @param $encrypt //传入加密串,在修改密码时做认证
  284. * @return array/password
  285. */
  286. function password($password, $encrypt='') {
  287. $pwd = array();
  288. $pwd['encrypt'] = $encrypt ? $encrypt : getRandChar();
  289. $pwd['password'] = md5(md5(trim($password)).$pwd['encrypt']);
  290. return $encrypt ? $pwd['password'] : $pwd;
  291. }
  292. /**
  293. * 生成随机字符串
  294. * @param string $lenth 长度
  295. * @return string 字符串
  296. */
  297. function randomstr($lenth = 6) {
  298. return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
  299. }
  300. /**
  301. * 生成随机数字串
  302. * @param string $lenth 长度
  303. * @return string 字符串
  304. */
  305. function randomnum() {
  306. $str = null;
  307. $strPol = "0123456789";
  308. $max = strlen($strPol)-1;
  309. for($i=0;$i<6;$i++){
  310. $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
  311. }
  312. return $str;
  313. }
  314. function getRandChar($length=6){
  315. $str = null;
  316. $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  317. $max = strlen($strPol)-1;
  318. for($i=0;$i<$length;$i++){
  319. $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
  320. }
  321. return $str;
  322. }
  323. function post_check($post)
  324. {
  325. if (!get_magic_quotes_gpc()) // 判断magic_quotes_gpc是否为打开
  326. {
  327. $post = addslashes($post); // 进行magic_quotes_gpc没有打开的情况对提交数据的过滤
  328. }
  329. $post = str_replace("_", "\_", $post); // 把 '_'过滤掉
  330. $post = str_replace("%", "\%", $post); // 把' % '过滤掉
  331. $post = nl2br($post); // 回车转换
  332. $post= htmlspecialchars($post); // html标记转换
  333. return $post;
  334. }
  335. /**
  336. * 发送get请求
  337. * @param string $url 请求地址
  338. * @param array $post_data post键值对数据
  339. * @return string
  340. */
  341. function send_get($url) {
  342. $ch = curl_init();
  343. curl_setopt($ch, CURLOPT_URL, $url);
  344. curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
  345. $result = curl_exec($ch);
  346. return $result;
  347. }
  348. /**
  349. * 发送post请求
  350. * @param string $url 请求地址
  351. * @param array $post_data post键值对数据
  352. * @return string
  353. */
  354. function send_post($url, $post_data) {
  355. $postdata = http_build_query($post_data);
  356. $options = array(
  357. 'http' => array(
  358. 'method' => 'POST',
  359. 'header' => 'Content-type:application/x-www-form-urlencoded',
  360. 'content' => $postdata,
  361. 'timeout' => 15 * 60 // 超时时间(单位:s)
  362. )
  363. );
  364. $context = stream_context_create($options);
  365. $result = file_get_contents($url, false, $context);
  366. return $result;
  367. }
  368. /**
  369. * php异步请求
  370. * $args array[
  371. * "host":主机
  372. * "url":地址
  373. * "method":方法
  374. * "data":数据
  375. * ]
  376. */
  377. function asyn_request($args) {
  378. $host = $args["host"] ? $args["host"] : "localhost";//主机
  379. $method = $args["method"] == "POST" ? "POST" : "GET";//方法
  380. $url = $args["url"] ? $args["url"] : "http://".$host ;//地址
  381. $data = is_array($args["data"]) ? $args["data"] : array();//请求参数
  382. $fp = @fsockopen($host,80,$errno,$errstr,30);
  383. //错误
  384. if(!$fp){echo"$errstr ($errno)<br/>\n";exit;}
  385. $qstr = http_build_query($data);//请求参数
  386. $params.= $method == "GET" ? "GET {$url}?{$qstr} HTTP/1.1\r\n" : "POST {$url} HTTP/1.1\r\n";
  387. $params.= "Host: ".$host."\r\n";
  388. $params.= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5\r\n";
  389. $params.= "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
  390. $params.= "Accept-Language: zh-cn,zh;q=0.5\r\n";
  391. $params.= "Accept-Encoding: gzip,deflate\r\n";
  392. $params.= "Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7\r\n";
  393. $params.= "Keep-Alive: 300\r\n";
  394. $params.= "Connection: keep-alive\r\n";
  395. $params.= "Content-Type: application/x-www-form-urlencoded\r\n";
  396. $params.= "Content-Length: ".strlen($qstr)."\r\n\r\n";
  397. $params.= $method == "GET" ? null :$qstr;
  398. //file_put_contents("C:\\http.txt",$params);
  399. fwrite($fp, $params);
  400. fclose($fp);
  401. /* $args["host"] = "localhost";//主机
  402. $args["url"] = "http://localhost/test/socket/doing.php";//异步执行的脚本
  403. $args["method"] = "POST";//请求方式
  404. $args["data"] = array("a"=>"中","b"=>"国");//参数
  405. asyn_request($args);*/
  406. }
  407. //发送XML返回数据
  408. function sendDataByCurl($url,$data){
  409. //Log::posthis("QuerySchedule:req2\r\n"."*a".call_user_func(array($_ENV["commonClass"],"timestamp")));
  410. $header[] = "Content-type: text/xml"; //定义content-type为xml,注意是数组
  411. $ch = curl_init ($url);
  412. curl_setopt($ch, CURLOPT_URL, $url);
  413. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  414. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  415. curl_setopt($ch, CURLOPT_HEADER, 0);
  416. curl_setopt($ch,CURLOPT_TIMEOUT,60); //定义超时3秒钟
  417. curl_setopt($ch, CURLOPT_POST, 1);
  418. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  419. $response = curl_exec($ch);
  420. //Log::posthis("QuerySchedule:req2\r\n"."*b".call_user_func(array($_ENV["commonClass"],"timestamp")));
  421. if(curl_errno($ch)){
  422. Log::cur_err(curl_error($ch));
  423. }
  424. curl_close($ch);
  425. //Log::posthis("QuerySchedule:req2\r\n"."*c".call_user_func(array($_ENV["commonClass"],"timestamp")));
  426. Log::posthis($url.$data);
  427. try{
  428. $xml = simplexml_load_string($response);
  429. header("Content-Type: text/html; charset=UTF-8");
  430. if($xml) {
  431. Log::gethis($response);
  432. } else {
  433. Log::xmlerr($response);
  434. }
  435. } catch(exception $e){
  436. Log::xmltc($e);
  437. }
  438. return $xml;
  439. }
  440. //发送XML返回数据
  441. function sendDataByCurlStr($url,$data){
  442. $header[] = "Content-type: text/xml"; //定义content-type为xml,注意是数组
  443. $ch = curl_init ($url);
  444. curl_setopt($ch, CURLOPT_URL, $url);
  445. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  446. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  447. curl_setopt($ch, CURLOPT_HEADER, 0);
  448. curl_setopt($ch,CURLOPT_TIMEOUT,60); //定义超时3秒钟
  449. curl_setopt($ch, CURLOPT_POST, 1);
  450. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  451. $response = curl_exec($ch);
  452. if(curl_errno($ch)){
  453. Log::cur_err(curl_error($ch));
  454. }
  455. curl_close($ch);
  456. Log::posthis($url.$data);
  457. try{
  458. $response= simplexml_load_string($response);
  459. header("Content-Type: text/html; charset=UTF-8");
  460. if($response) {
  461. Log::gethis($response);
  462. } else {
  463. Log::xmlerr($response);
  464. }
  465. } catch(exception $e){
  466. Log::xmltc($e);
  467. }
  468. return $response;
  469. }
  470. function SoapToXml($xml)
  471. {
  472. //api测试先关闭
  473. $startStr=strrpos($xml,"<![CDATA[");
  474. $endStr=strpos($xml,"]]>");
  475. $xml=substr($xml,$startStr,$endStr-$startStr);
  476. $xml = str_replace("<![CDATA[>","",$xml);
  477. $xml = str_replace("<![CDATA[","",$xml);
  478. $xml = str_replace("]]]]>","",$xml);
  479. $xml = str_replace("]]>","",$xml);
  480. $xml = str_replace("<ILLEGAL VALUE>","",$xml);
  481. return $xml;
  482. }
  483. }
  484. ?>