Repository navigation
Expand file tree
/
Copy pathcurl.php
More file actions
102 lines (84 loc) · 2.9 KB
/
Copy pathcurl.php
File metadata and controls
102 lines (84 loc) · 2.9 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
<?php
class Curl {
var $channel;
private $headers = array();
function __construct()
{
$this->reset();
}
function reset()
{
$this->channel = curl_init( );
// you might want the headers for http codes
curl_setopt($this->channel, CURLOPT_HEADER, true );
// you wanna follow stuff like meta and location headers
curl_setopt($this->channel, CURLOPT_FOLLOWLOCATION, true );
// you want all the data back to test it for errors
curl_setopt($this->channel, CURLOPT_RETURNTRANSFER, true );
// probably unecessary, but cookies may be needed to
curl_setopt($this->channel, CURLOPT_COOKIEJAR, 'cookie.txt');
// as above
curl_setopt($this->channel, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt($this->channel, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($this->channel, CURLOPT_TIMEOUT, 30);
}
function setOption($option, $value) {
curl_setopt( $this->channel, $option, $value);
}
function addHeader($name, $value) {
$this->headers[$name] = $value;
}
function setUserAgent($useragent) {
$this->setOption('CURLOPT_USERAGENT', $useragent);
}
function setPostFields($vars) {
curl_setopt( $this->channel, CURLOPT_POSTFIELDS, $vars );
curl_setopt( $this->channel, CURLOPT_POST, true );
}
function post($url) {
curl_setopt( $this->channel, CURLOPT_POST, true );
curl_setopt( $this->channel, CURLOPT_HTTPHEADER, $this->headers );
return $this->makeRequest($url);
}
function get($url) {
curl_setopt( $this->channel, CURLOPT_HTTPGET, true );
curl_setopt( $this->channel, CURLOPT_HTTPHEADER, $this->headers );
return $this->makeRequest($url);
}
function makeRequest($url)
{
// setup the url to post / get from / to
curl_setopt( $this->channel, CURLOPT_URL, $url );
// the actual post bit
// return data
$response = curl_exec( $this->channel );
$sections = explode("\r\n\r\n", $response, 2);
if (count($sections) != 2) {
//var_dump($sections);
throw new exception("Error retrieving data");
}
list($header, $body) = $sections;
$header = explode("\n", $header);
$status = array_shift($header);
$status = substr($status, 9, 3);
$headers = array();
foreach ($header as $line) {
list ($key, $value) = explode(":", $line, 2);
$headers[$key] = trim($value);
}
$response = new CurlResponse();
$response->status = $status;
$response->header = $headers;
$response->content = $body;
return $response;
}
}
class CurlResponse {
public $content;
public $status;
public $headers;
public function jsonContent() {
return json_decode($this->content);
}
}
?>