httpjson.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. function httpjson($endpoint,$timeout=null,$method=null,$postdata=null,$accept=null,$token=null,$okcodes=null) {
  3. if (is_null($timeout)) $timeout=5;
  4. if (is_null($method)) $method='GET';
  5. if (is_null($accept)) $accept='application/json';
  6. if (is_null($okcodes)) $okcodes=[200];
  7. $context=[
  8. 'http'=>[
  9. 'timeout'=>$timeout,
  10. 'method'=>$method,
  11. 'user_agent'=>'Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0',
  12. 'header'=>"Accept: {$accept}\r\n",
  13. 'ignore_errors'=>true
  14. ]
  15. ];
  16. if (!is_null($token)) $context['http']['header'].="Authorization: Bearer {$token}\r\n";
  17. if (!is_null($postdata)) {
  18. $context['http']['header'].="Content-type: application/x-www-form-urlencoded\r\n";
  19. $context['http']['content']=http_build_query($postdata);
  20. }
  21. $context=stream_context_create($context);
  22. $headers=[];
  23. $errors=[];
  24. $ret=['ok'=>false,'headers'=>[],'content'=>[],'errors'=>null];
  25. $http_response_header=null;
  26. $res=@file_get_contents($endpoint,false,$context);
  27. if ($res===false) {
  28. $errors[]="could not connect";
  29. } else {
  30. if (is_array($http_response_header)) {
  31. $httprc=null;
  32. $li=count($http_response_header)-1;
  33. for ($i=$li; $i>=0; $i--) {
  34. array_unshift($headers,$http_response_header[$i]);
  35. if (preg_match('#HTTP/\S+\s+(\d+)#',$http_response_header[$i],$matches)===1) {
  36. $httprc=$matches[1]+0;
  37. break;
  38. }
  39. }
  40. if (is_null($httprc))
  41. $errors[]="got no HTTP response status code";
  42. elseif (!in_array($httprc,$okcodes))
  43. $errors[]="got «{$httprc}» HTTP response status code";
  44. } else {
  45. $errors[]="«got no headers";
  46. }
  47. $res=@json_decode($res,true);
  48. if ($res===false) {
  49. $errors[]="got no valid JSON";
  50. } else {
  51. if (count($errors)>0 && isset($res['error']))
  52. $errors[]=$res['error'];
  53. $ret['content']=$res;
  54. }
  55. }
  56. if (count($errors)==0)
  57. $ret['ok']=true;
  58. $errors=implode('; ',$errors);
  59. $ret['headers']=$headers;
  60. $ret['errors']=$errors;
  61. return $ret;
  62. }
  63. ?>