1: <?php
2: 3: 4: 5: 6: 7:
8:
9: namespace ApiAxle\Shared;
10:
11: 12: 13: 14: 15: 16: 17: 18: 19: 20:
21: class HttpRequest
22: {
23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37:
38: public static function request($uri,$method='GET',$postfields=false,$headers=false,$config=false) {
39: $ch = curl_init();
40: curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
41: curl_setopt($ch, CURLOPT_URL, $uri);
42: curl_setopt($ch, CURLINFO_HEADER_OUT, true);
43: if($config){
44: curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $config->getSslVerifypeer());
45: if($config->getSslVerifypeer()){
46: if(!is_null($config->getSslCainfo())){
47: curl_setopt($ch, CURLOPT_CAINFO, $config->getSslCainfo());
48: }
49: if(!is_null($config->getSslCapath())){
50: curl_setopt($ch, CURLOPT_CAPATH, $config->getSslCapath());
51: }
52: }
53:
54: if($config->getProxyEnable()){
55: curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, $config->getProxyEnable());
56: curl_setopt($ch, CURLOPT_PROXY, $config->getProxyHost());
57: curl_setopt($ch, CURLOPT_PROXYPORT, $config->getProxyPort());
58: }
59: }
60:
61: $method = strtoupper($method);
62: if($method == 'GET'){
63: curl_setopt($ch, CURLOPT_HTTPGET, true);
64: } elseif($method == 'POST') {
65: curl_setopt($ch, CURLOPT_POST, true);
66: } elseif($method == 'PUT'){
67: curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
68: } elseif($method == 'DELETE'){
69: curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
70: }
71:
72: if($postfields && ($method == 'POST' || $method == 'PUT')){
73: curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
74: }
75: if($headers && is_array($headers)){
76: curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
77: }
78:
79: $response = curl_exec($ch);
80: $info = curl_getinfo($ch);
81: if($response){
82: return $response;
83: } else {
84: if($info['http_code'] == 204){
85: $result = array(
86: 'success' => true
87: );
88: return json_encode($result);
89: } else {
90: $curl_errno = curl_errno($ch);
91: if($curl_errno == 0){
92: $code = $info['http_code'];
93: } else {
94: $code = $curl_errno;
95: }
96: throw new \ErrorException('Http Request Failed: '.$uri.' (HTTP Status: '.$info['http_code'].') with error: '.
97: curl_error($ch), 210);
98: }
99: }
100: }
101: }