Skip to content

Instantly share code, notes, and snippets.

@hemant-tivlabs
Last active September 30, 2020 15:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hemant-tivlabs/2f01dd811474591c080c873adc3924fe to your computer and use it in GitHub Desktop.
Save hemant-tivlabs/2f01dd811474591c080c873adc3924fe to your computer and use it in GitHub Desktop.
A more configurable PHP cURL request function
<?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