/** * Generic REST PHP client (Tested) * @see $this->rest_call('https://httpbin.org', '/post', 'POST', array('test' => date('Y-m-d H:i:s')), array(CURLAUTH_DIGEST, 'user', 'pass'), true); * @param string $path * @param string $method * @param array $vars * @param array $auth * @param boolean $debug * @return boolean || string */ function rest_call($url, $path = '', $method = 'GET', $vars = array(), $auth = array(), $debug = false) { defined('ERROR_LOG') or define('ERROR_LOG', tempnam(sys_get_temp_dir(),'REST')); defined('PHP_VERSION_ID') or define('PHP_VERSION_ID', preg_replace('/[^0-9A-Za-z\.]/', '', PHP_VERSION)); if (empty($url)) { file_put_contents(ERROR_LOG, "REST call url not set\n", FILE_APPEND); return false; } $url .= $path; $tmpfile = ''; $postdata = http_build_query($vars, '', '&'); if ($method == 'GET' && count($vars) > 0) { $url .= '?' . $postdata; } $ch = curl_init($url); if ($debug) { curl_setopt($ch, CURLOPT_VERBOSE, 1); $fp = fopen(ERROR_LOG, 'w'); curl_setopt($ch, CURLOPT_STDERR, $fp); } switch ($method) { case 'GET': curl_setopt($ch, CURLOPT_HTTPGET, true); break; case 'POST': curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); break; case 'PUT': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); file_put_contents($tmpfile = tempnam(sys_get_temp_dir(),'RESTPUT'), $postdata); curl_setopt($ch, CURLOPT_INFILE, $fp = fopen($tmpfile, 'r')); curl_setopt($ch, CURLOPT_INFILESIZE, filesize($tmpfile)); break; case 'DELETE': curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE'); curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata); break; default: curl_setopt($ch, CURLOPT_HTTPGET, true); break; } if (isset($auth[0]) && isset($auth[1]) && isset($auth[2])) { switch ($auth[0]) { case 'basic': case CURLAUTH_BASIC: curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, $auth[1].':'.$auth[2]); break; case 'digest': case CURLAUTH_DIGEST: curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST); curl_setopt($ch, CURLOPT_USERPWD, $auth[1].':'.$auth[2]); break; case 'none': case CURLAUTH_NONE: default: curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_NONE); break; } } curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; REST PHP caller; PHP/'.PHP_VERSION_ID.')'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); curl_setopt($ch, CURLOPT_TIMEOUT, 5); $res = curl_exec($ch); $errno = curl_errno($ch); $errmsg = curl_error($ch); $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if (strlen($tmpfile)) { unlink($tmpfile); } if ($debug) { fclose($fp); } if ($res === false || $errno != 0) { file_put_contents(ERROR_LOG, "REST call error {$errmsg}\n", FILE_APPEND); return false; } if ($http_status != 200) { file_put_contents(ERROR_LOG, "REST call http status {$http_status}\n", FILE_APPEND); return false; } return $res; }