Skip to content

Instantly share code, notes, and snippets.

@matesnippets
Created November 18, 2015 19:27
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 matesnippets/3d2e4577a08ed08206a6 to your computer and use it in GitHub Desktop.
Save matesnippets/3d2e4577a08ed08206a6 to your computer and use it in GitHub Desktop.
PHP, simply REST API caller function
/**
* Call an API
*
* @param string $method HTTP verb: POST, PUT, GET etc
* @param stinrg $url URL
* @param boolean $data Plunk the data tot he URL: array("param" => "value") ==> index.php?param=value
* @return request Whatever the API returns
*/
function n26_call_api($method, $url, $data = false) {
$curl = curl_init();
switch ($method) {
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data) {
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data) {
$url = sprintf("%s?%s", $url, http_build_query($data));
}
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment