Last active
February 18, 2017 07:28
-
-
Save hidayat365/9828411 to your computer and use it in GitHub Desktop.
REST Helper Function using PHP
This file contains hidden or 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
/* | |
* REST_Helper: Helper untuk mengakses layanan REST | |
* Bisa digunakan walaupun fungsi cURL diblokir | |
* | |
* @param string $url URL yang mau kita buka | |
* @param optional array $params data yang mau kita POST ke $url | |
* @param optional string method either POST or GET | |
* @param optional string format payload | |
*/ | |
function rest_helper($url, $params = null, $verb = 'GET', $format = 'text') | |
{ | |
$cparams = array( | |
'http'=>array( | |
'method' => $verb, | |
'ignore_errors' = >true | |
) | |
); | |
if ($params !== null) { | |
$params = http_build_query($params); | |
if ($verb == 'POST') { | |
$cparams['http']['content'] = $params; | |
} else { | |
$url .= '?' . $params; | |
} | |
} | |
$context = stream_context_create($cparams); | |
$fp = fopen($url, 'rb', false, $context); | |
if (!$fp) { | |
$res = false; | |
} else { | |
// If you're trying to troubleshoot problems, try uncommenting the next two lines; | |
// it will show you the HTTP response headers across all the redirects: | |
// $meta = stream_get_meta_data($fp); | |
// var_dump($meta['wrapper_data']); | |
$res = stream_get_contents($fp); | |
} | |
if ($res === false) { | |
throw new Exception("$verb $url failed: $php_errormsg"); | |
} | |
switch ($format) { | |
case 'json': | |
$r = json_decode($res); | |
if ($r === null) { | |
throw new Exception("failed to decode $res as json"); | |
} | |
return $r; | |
case 'xml': | |
$r = simplexml_load_string($res); | |
if ($r === null) { | |
throw new Exception("failed to decode $res as xml"); | |
} | |
return $r; | |
} | |
return $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment