1 /**
2 * @desc curl request请求
3 * @date 2016-12-07 16:26:55
4 *
5 * @param $arguments
6 *
7 * @return bool|mixed
8 *
9 * @internal param 请求的url $url
10 * @internal param int|post为1 $ispost
11 * @internal param array|参数 $params
12 * @internal param string|请求的头部数据 $header
13 * @internal param string|请求的cookie数据 $cookie
14 * @internal param bool|请求数据错误是否返回获取的数据 $source
15 *
16 */
17 function curlRequest($arguments = array())
18 {
19 $url = $arguments['url'];
20 $ispost = isset($arguments['ispost']) ? $arguments['ispost'] : 0;
21 $params = isset($arguments['params']) ? $arguments['params'] : array();
22 $header = isset($arguments['header']) ? $arguments['header'] : "";
23 $cookie = isset($arguments['cookie']) ? $arguments['cookie'] : "";
24 $source = isset($arguments['source']) ? $arguments['source'] : TRUE;
25
26
27 $ch = curl_init($url);
28 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
29 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
30 curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // 将curl_exec()获取的信息以文件流的形式返回,而不是直接输出。
31 curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数 30s
32 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10); // 在发起连接前等待的时间,如果设置为0,则无限等待。
33 curl_setopt($ch, CURLOPT_HEADER, $header); // 设置请求头部header数据
34
35 // post and 参数
36 if ($ispost) {
37 curl_setopt($ch, CURLOPT_POST, TRUE); // 是否使用post方式请求
38 curl_setopt($ch, CURLOPT_POSTFIELDS, $params); // post 请求数据
39 curl_setopt($ch, CURLOPT_URL, $url);
40 } else {
41 if ($params) {
42 if (is_array($params)) {
43 $params = http_build_query($params);
44 }
45 curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
46 } else {
47 curl_setopt($ch, CURLOPT_URL, $url);
48 }
49 }
50
51 // 设置cookie
52 if ($cookie) {
53 curl_setopt($ch, CURLOPT_COOKIE, $cookie);
54 }
55
56 //抓取URL并把它传递给浏览器
57 $result = curl_exec($ch);
58 //var_dump($result);
59 // 为false 说明curl错误
60 if($result === false) {
61 $result = 'ERROR(CURL): ['.curl_errno($ch) . ']' . curl_error($ch);
62 }
63
64 //获取执行后的 http 状态码
65 $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
66 if ($httpCode != 200 && !$source) { // 非200说明异常
67 $result = FALSE;
68 }
69
70 // [DEBUG]获取执行后的 http 头部Header
71 if ($httpCode != 200 && isset($_GET['debug'])) {
72 $httpInfo = curl_getinfo($ch);
73 echo '<pre>' . print_r($httpInfo, true) . '</pre>' . PHP_EOL;
74 }
75
76 curl_close($ch); // 关闭cURL资源,并且释放系统资源
77
78 return $result;
79 }