PHP使用CURL请求API接口并返回数组

红太狼 2021-01-08 14:18 1172阅读 0赞
  1.    /**
  2. * curl 函数,接口调用
  3. * @param string $url 请求的地址
  4. * @param string $type POST/GET/post/get
  5. * @param array $data 要传输的数据
  6. * @param string $err_msg 可选的错误信息(引用传递)
  7. * @param int $timeout 超时时间
  8. * @param array $cert_info 证书信息
  9. * @author
  10. */
  11. function go_curl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
  12. {
  13. $type = strtoupper($type);
  14. if ($type == 'GET' && is_array($data)) {
  15. $data = http_build_query($data);
  16. }
  17. $option = array();
  18. if ( $type == 'POST' ) {
  19. $option[CURLOPT_POST] = 1;
  20. }
  21. if ($data) {
  22. if ($type == 'POST') {
  23. $option[CURLOPT_POSTFIELDS] = $data;
  24. } elseif ($type == 'GET') {
  25. $url = strpos($url, '?') !== false ? $url.'&'.$data : $url.'?'.$data;
  26. }
  27. }
  28. $option[CURLOPT_URL] = $url;
  29. $option[CURLOPT_MAXREDIRS] = 4;
  30. $option[CURLOPT_RETURNTRANSFER] = TRUE;
  31. $option[CURLOPT_TIMEOUT] = $timeout;
  32. //设置证书信息
  33. if(!empty($cert_info) && !empty($cert_info['cert_file'])) {
  34. $option[CURLOPT_SSLCERT] = $cert_info['cert_file'];
  35. $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
  36. $option[CURLOPT_SSLCERTTYPE] = $cert_info['cert_type'];
  37. }
  38. //设置CA
  39. if(!empty($cert_info['ca_file'])) {
  40. // 对认证证书来源的检查,0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
  41. $option[CURLOPT_SSL_VERIFYPEER] = 1;
  42. $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
  43. } else {
  44. // 对认证证书来源的检查,0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
  45. $option[CURLOPT_SSL_VERIFYPEER] = 0;
  46. }
  47. $ch = curl_init();
  48. curl_setopt_array($ch, $option);
  49. $response = curl_exec($ch);
  50. $curl_no = curl_errno($ch);
  51. $curl_err = curl_error($ch);
  52. curl_close($ch);
  53. // error_log
  54. if($curl_no > 0) {
  55. if($err_msg !== null) {
  56. $err_msg = '('.$curl_no.')'.$curl_err;
  57. }
  58. }
  59. return json_decode($response,true);
  60. }

发表评论

表情:
评论列表 (有 0 条评论,1172人围观)

还没有评论,来说两句吧...

相关阅读

    相关 使用curl请求接口

    当没有接口工具调用服务时, 可以通过curl命令来请求服务以获取结果或检测接口是否可用.  参数: \-H : 指定请求头, 或者指定请求头里面的参数, 可以有多个该参数