Skip to content

Instantly share code, notes, and snippets.

@fhdalikhan
Created July 26, 2019 13:56
Show Gist options
  • Save fhdalikhan/8e1ea27cb400ec2b6d4709a9b97e710b to your computer and use it in GitHub Desktop.
Save fhdalikhan/8e1ea27cb400ec2b6d4709a9b97e710b to your computer and use it in GitHub Desktop.
Curl Example PHP
<?php
class CurlTest {
const API_BASE_URL = 'http://example.com/v1/';
protected $apiKey = 'YOUR API KEY';
protected function _getApiData($route, $method = 'GET', $sendData = array()){
$method = strtoupper($method);
$requestUrl = self::API_BASE_URL.$route;
$curlObj = curl_init();
curl_setopt($curlObj, CURLOPT_URL,$requestUrl);
if($method == 'GET'){
curl_setopt($curlObj, CURLOPT_HTTPGET,true);
}elseif($method == 'POST'){
curl_setopt($curlObj, CURLOPT_POST, true);
}elseif ($method == 'PUT'){
curl_setopt($curlObj, CURLOPT_CUSTOMREQUEST, "PUT");
}else{
curl_setopt($curlObj, CURLOPT_CUSTOMREQUEST, $method);
}
curl_setopt($curlObj, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($curlObj, CURLOPT_TIMEOUT, 90);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_HEADER, 0);
$headers = array(
'Trackingmore-Api-Key: ' . $this->apiKey,
'Content-Type: application/json',
);
if($sendData){
$dataString = json_encode($sendData);
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $dataString);
$headers[] = 'Content-Length: ' . strlen($dataString);
}
curl_setopt($curlObj, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curlObj);
curl_close($curlObj);
unset($curlObj);
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment