-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCurlClient.php
More file actions
107 lines (89 loc) · 2.5 KB
/
CurlClient.php
File metadata and controls
107 lines (89 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* A wrapper for cURL
*/
class CurlClient
{
/** @var resource */
public $curl;
/** @var array */
public $headers;
/**
* create a cURL instance
*/
public function __construct($verbose = true)
{
$this->curl = curl_init();
curl_setopt_array(
$this->curl,
array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_VERBOSE => $verbose,
CURLOPT_HEADERFUNCTION => array($this, 'header'),
CURLOPT_ENCODING => '',
)
);
}
/**
* Make a GET request
* Either save the response to a file, or return it
*
* @param string $url
* @param array $params
* @param null $file
* @param int $tries
*
* @return bool|mixed
* @throws Exception
*/
public function get($url, $headers = array(), $file = null, $tries = 0)
{
$this->report(sprintf('Fetching %s', $url));
curl_setopt_array($this->curl, array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_FILE => is_null($file) ? STDOUT : $file, // STDOUT if no file
));
// reset the headers array
$this->headers = array();
$result = curl_exec($this->curl);
$info = curl_getinfo($this->curl);
// remove local details
unset($info['local_ip']);
unset($info['local_port']);
$info['headers'] = $this->headers;
return $info;
}
/**
* Store response headers in an array
*
* @param $curl
* @param $header
*
* @return int header length
*/
protected function header($curl, $header) {
$parts = preg_split('/:\s+/', $header, 2);
if (isset($parts[1])) {
list($name, $value) = $parts;
$name = strtolower($name);
$value = rtrim($value);
if (isset($this->headers[$name])) {
// append multiple headers with a comma separator
$this->headers[$name] .= ', ' . $value;
} else {
$this->headers[$name] = $value;
}
}
return strlen($header);
}
/**
* Output messages to stderr
*/
protected function report($output = '', $suffix = "\n") {
file_put_contents('php://stderr', $output . $suffix);
}
}