Last active
December 17, 2018 10:52
-
-
Save terremoth/6bc3431f684d55968a558e59b75aacf2 to your computer and use it in GitHub Desktop.
Curl Request WS API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class HttpRequest | |
{ | |
protected $url; | |
protected $headers = array(); | |
public $httpCode; | |
private $sslVerify = false; | |
public function request($data, $rawMethod = 'POST', $sendMode = 'json') | |
{ | |
$method = strtoupper($rawMethod); | |
$buildedData = $this->buildSendData($sendMode, $data); | |
$curl = curl_init(); | |
curl_setopt($curl, CURLOPT_URL, $this->url); | |
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->sslVerify); | |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); | |
if ($method == 'POST') { | |
curl_setopt($curl, CURLOPT_POST, true); | |
} else { | |
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method); | |
} | |
if ($buildedData) { | |
curl_setopt($curl, CURLOPT_POSTFIELDS, $buildedData); | |
} | |
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->headers); | |
$response = curl_exec($curl); | |
$this->httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); | |
curl_close($curl); | |
return $response; | |
} | |
public function buildSendData($sendMode, $data) | |
{ | |
switch ($sendMode) { | |
default: | |
case 'raw': $buildedData = urlencode($data); break; | |
case 'json': $buildedData = json_encode($data); break; | |
case 'query': $buildedData = http_build_query($data); break; | |
case 'xml': | |
$xml = new SimpleXMLElement($data); | |
$buildedData = $xml->asXML(); | |
break; | |
} | |
return $buildedData; | |
} | |
protected function setUrl($url) | |
{ | |
$this->url = $url; | |
} | |
protected function addInUrl($str) | |
{ | |
$this->url .= $str; | |
} | |
protected function useSsl($use = true) | |
{ | |
$this->sslVerify = $use; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment