Skip to content

Instantly share code, notes, and snippets.

@johnie
Created August 26, 2016 07:51
Show Gist options
  • Save johnie/5444cc8c1a4fb726660dc42a0335d37a to your computer and use it in GitHub Desktop.
Save johnie/5444cc8c1a4fb726660dc42a0335d37a to your computer and use it in GitHub Desktop.
Make Curl call
<?php
/**
* Make Curl call.
*
* @param string $url URL to curl
* @param string $method GET or POST, Default GET
* @param mixed $data Data to post, Default false
* @param mixed $headers Additional headers, example: array ("Accept: application/json")
* @param bool $returnInfo Whether or not to retrieve curl_getinfo()
*
* @return string|array if $returnInfo is set to True, array is returned with two keys, contents (will contain response) and info (information regarding a specific transfer), otherwise response content is returned
*/
public static function curl($url, $method = 'GET', $data = false, $headers = false, $returnInfo = false) {
$ch = curl_init();
$info = null;
if (strtoupper($method) == 'POST') {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
if ($data !== false) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
} else {
if ($data !== false) {
if (is_array($data)) {
$dataTokens = [];
foreach ($data as $key => $value) {
array_push($dataTokens, urlencode($key).'='.urlencode($value));
}
$data = implode('&', $dataTokens);
}
curl_setopt($ch, CURLOPT_URL, $url.'?'.$data);
} else {
curl_setopt($ch, CURLOPT_URL, $url);
}
}
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
if ($headers !== false) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$contents = curl_exec($ch);
if ($returnInfo) {
$info = curl_getinfo($ch);
}
curl_close($ch);
if ($returnInfo) {
return ['contents' => $contents, 'info' => $info];
} else {
return $contents;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment