Skip to content

Instantly share code, notes, and snippets.

@johnsardine
Last active December 13, 2015 22:59
Show Gist options
  • Save johnsardine/4988388 to your computer and use it in GitHub Desktop.
Save johnsardine/4988388 to your computer and use it in GitHub Desktop.
REST Request PHP with CURL
function curl_request($url, $parameters = array(), $type = 'GET') {
$type = strtoupper($type);
$request = curl_init();
if ($type === 'POST' && !empty($parameters)) {
curl_setopt($request, CURLOPT_POST, count($parameters));
curl_setopt($request, CURLOPT_POSTFIELDS, http_build_query($parameters));
} else if (!empty($parameters)) {
$url = $url.'?'.http_build_query($parameters);
}
$request_options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => $type,
);
curl_setopt_array($request, $request_options);
$response = curl_exec($request);
curl_close($request);
// If the response is a valid json array, return array
$response_json = json_decode($response, true);
if (is_array($response_json))
$response = $response_json;
return $response;
}
$response = curl_request(
$url,
array(
'foo' => 'bar',
'bar' => array('vodka', 'martini')
),
'GET'
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment