Created
April 10, 2014 10:37
-
-
Save n1shantshrivastava/10366578 to your computer and use it in GitHub Desktop.
RequestGenerator, a simple PHP class for handling Curl Request.
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 : RequestGenerator | |
* Type : Component | |
* @author Nishant Shrivastava <[email protected]> | |
*/ | |
class RequestGeneratorComponent extends CComponent { | |
/** | |
* Default options for curl. | |
*/ | |
public static $CURL_OPTS = array( | |
'CURLOPT_CONNECTTIMEOUT' => 30, | |
'CURLOPT_RETURNTRANSFER' => true, | |
'CURLOPT_TIMEOUT' => 60, | |
'CURLOPT_USERAGENT' => 'request-generator-webonise-1.0', | |
); | |
function __construct() { | |
if (!function_exists('curl_init')) { | |
throw new Exception('Application needs the CURL PHP extension.'); | |
} | |
if (!function_exists('json_decode')) { | |
throw new Exception('Application needs the JSON PHP extension.'); | |
} | |
} | |
/** | |
* Make an HTTP request | |
* | |
* @return API results | |
*/ | |
public function request($url, $method = 'GET', $postFields = NULL) { | |
$this->http_info = $response = array(); | |
$curlObj = curl_init(); | |
/* Curl settings */ | |
$curlOptions = self::$CURL_OPTS; | |
curl_setopt($curlObj, CURLOPT_USERAGENT, $curlOptions['CURLOPT_USERAGENT']); | |
curl_setopt($curlObj, CURLOPT_CONNECTTIMEOUT, $curlOptions['CURLOPT_CONNECTTIMEOUT']); | |
curl_setopt($curlObj, CURLOPT_TIMEOUT, $curlOptions['CURLOPT_TIMEOUT']); | |
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, $curlOptions['CURLOPT_RETURNTRANSFER']); | |
curl_setopt($curlObj, CURLOPT_HEADER, FALSE); | |
switch ($method) { | |
case 'POST': | |
curl_setopt($curlObj, CURLOPT_POST, TRUE); | |
if (!empty($postFields)) { | |
curl_setopt($curlObj, CURLOPT_POSTFIELDS, $postFields); | |
} | |
continue; | |
case 'DELETE': | |
curl_setopt($curlObj, CURLOPT_CUSTOMREQUEST, 'DELETE'); | |
if (!empty($postFields)) { | |
$url = "{$url}?{$postFields}"; | |
} | |
continue; | |
default: | |
continue; | |
} | |
curl_setopt($curlObj, CURLOPT_URL, $url); | |
try { | |
$response = curl_exec($curlObj); | |
$response = json_decode($response, true); | |
} catch (Exception $e) { | |
die('Curl Exception [' . $e->getCode() . '] : ' . $e->getMessage()); | |
} | |
/** | |
* @internal Capturing http code and http info and merging it into response array | |
*/ | |
$response['http_info'] = curl_getinfo($curlObj); | |
curl_close($curlObj); | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment