forked from M1ke/easy-site-utils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.php
70 lines (64 loc) · 1.69 KB
/
http.php
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
<?php
function http_get_json($url, $json_depth=512){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER,[
'Content-Type: application/json',
'Accept: application/json'
]);
$response = curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($retcode!=200){
throw new \Exception('CURL failed to return a valid response');
}
$result=json_decode($response, true, $json_depth);
if ($result===null){
throw new \Exception('The JSON could not be parsed correctly: "'.json_error_msg().'"');
}
return $result;
}
function http_post_curl($post,$url,$return=false){
//url-ify the data for the POST
foreach($post as $key => $value){
$value=urlencode($value);
$post_string.=$key.'='.$value.'&';
}
rtrim($post_string,'&');
//open connection
$ch=curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($post));
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string);
if ($return){
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
}
//execute post
$result=curl_exec($ch);
//close connection
curl_close($ch);
return $result;
}
function http_stream($url,$data,$content='post'){
switch ($content){
case 'post':
$data=http_build_query($data);
$content_type="application/x-www-form-urlencoded";
break;
case 'xml':
$content_type='text/xml';
break;
}
$options=array(
'http'=>array(
'header'=>"Content-type: $content_type\r\n",
'method'=>'POST',
'content'=>$data,
),
);
$context=stream_context_create($options);
$result=file_get_contents($url,false,$context);
return $result;
}