Created
July 26, 2019 13:56
-
-
Save fhdalikhan/8e1ea27cb400ec2b6d4709a9b97e710b to your computer and use it in GitHub Desktop.
Curl Example PHP
This file contains hidden or 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 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