Last active
September 30, 2020 15:50
-
-
Save hemant-tivlabs/2f01dd811474591c080c873adc3924fe to your computer and use it in GitHub Desktop.
A more configurable PHP cURL request function
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 | |
function curl_request($url, $method = 'POST', $params = array(), $options = array()) { | |
try { | |
$options_defaults = array( | |
'headers' => array(), | |
'json_response' => true, | |
'connecttimeout' => null, | |
'timeout' => null, | |
'returnresponsecode' => false | |
); | |
foreach($options_defaults as $od_key => $od_value) { | |
if(!isset($options[$od_key])) { | |
$options[$od_key] = $options_defaults[$od_key]; | |
} | |
} | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); | |
if(!empty($options['headers'])) { | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $options['headers']); | |
} | |
if(!empty($params)) { | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); | |
} | |
if(!empty($options['connecttimeout'])) { | |
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $options['connecttimeout']); | |
} | |
if(!empty($options['timeout'])) { | |
curl_setopt($ch, CURLOPT_TIMEOUT, $options['timeout']); | |
} | |
$output = curl_exec($ch); | |
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
curl_close($ch); | |
if(!empty($options['returnresponsecode'])) { | |
$output_new = new stdClass(); | |
$output_new->httpcode = $httpcode; | |
$output_new->output = true === $options['json_response'] ? json_decode($output) : $output; | |
return $output_new; | |
} else { | |
return true === $options['json_response'] ? json_decode($output) : $output; | |
} | |
} catch(Exception $e) { | |
if(true === $options['json_response']) | |
return json_decode('{"error":true,"message":"'.$e->getMessage().'"}'); | |
else | |
throw new Exception($e->getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment