1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?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'=>'Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0',
- '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\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 ($res===false) {
- $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;
- }
- ?>
|