Skip to content

Instantly share code, notes, and snippets.

@terremoth
Last active Dec 17, 2018
Embed
What would you like to do?
Curl Request WS API
<?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