pfaltgall/lib/httpjson.php

65 lines
1.9 KiB
PHP

<?php
function httpjson($endpoint,$timeout=null,$method=null,$postdata=null,$accept=null,$token=null,$okcodes=null) {
if (is_null($timeout)) $timeout=5;
if (is_null($method)) $method='GET';
if (is_null($accept)) $accept='application/json';
if (is_null($okcodes)) $okcodes=[200];
$context=[
'http'=>[
'timeout'=>$timeout,
'method'=>$method,
'user_agent'=>'httpjson/1.1',
'header'=>"Accept: {$accept}\r\n",
'ignore_errors'=>true
]
];
if (!is_null($token)) $context['http']['header'].="Authorization: Bearer {$token}\r\n";
if (!is_null($postdata)) {
$context['http']['header'].="Content-type: application/x-www-form-urlencoded\r\nIdempotency-Key: ".md5(implode('-',$postdata).time())."\r\n";
$context['http']['content']=http_build_query($postdata);
}
$context=stream_context_create($context);
$headers=[];
$errors=[];
$ret=['ok'=>false,'headers'=>[],'content'=>[],'errors'=>null];
$http_response_header=null;
$res=@file_get_contents($endpoint,false,$context);
if ($res===false) {
$errors[]="could not connect";
} else {
if (is_array($http_response_header)) {
$httprc=null;
$li=count($http_response_header)-1;
for ($i=$li; $i>=0; $i--) {
array_unshift($headers,$http_response_header[$i]);
if (preg_match('#HTTP/\S+\s+(\d+)#',$http_response_header[$i],$matches)===1) {
$httprc=$matches[1]+0;
break;
}
}
if (is_null($httprc))
$errors[]="got no HTTP response status code";
elseif (!in_array($httprc,$okcodes))
$errors[]="got «{$httprc}» HTTP response status code";
} else {
$errors[]="«got no headers";
}
$res=@json_decode($res,true);
if (is_null($res)) {
$errors[]="got no valid JSON";
} else {
if (count($errors)>0 && isset($res['error']))
$errors[]=$res['error'];
$ret['content']=$res;
}
}
if (count($errors)==0)
$ret['ok']=true;
$errors=implode('; ',$errors);
$ret['headers']=$headers;
$ret['errors']=$errors;
return $ret;
}
?>