CurlHelper.php 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. <?php
  2. namespace common\helpers;
  3. use GuzzleHttp\Client;
  4. use yii\helpers\Json;
  5. /*
  6. * @Descripttion: CURL 方法
  7. * @version:
  8. * @Author: ewgof
  9. * @Date: 2021-07-08 16:14:39
  10. * @LastEditors: ewgof
  11. * @LastEditTime: 2022-03-22 14:46:16
  12. */
  13. class CurlHelper
  14. {
  15. private static $config = [
  16. 'timeout' => 2.0,
  17. 'debug' => false,
  18. ];
  19. public static function get(string $url, array $params = [], array $headers = [])
  20. {
  21. if (!empty($params)) {
  22. $url .= '?';
  23. foreach ($params as $pk => $pv) {
  24. if (is_array($pv)) {
  25. foreach ($pv as $key => $item) {
  26. $url .= $pk . "[{$key}]=" . $item . '&';
  27. }
  28. } else {
  29. $url .= $pk . '=' . $pv . '&';
  30. }
  31. }
  32. $url = rtrim($url, '&');
  33. }
  34. if (empty($headers)) {
  35. $rst = self::request($url);
  36. } else {
  37. $rst = self::request($url, 'get', [], $headers);
  38. }
  39. return $rst;
  40. }
  41. public static function post(string $url, array $data = [], array $headers = [], string $format = 'json')
  42. {
  43. return self::request($url, 'post', $data, $headers, $format);
  44. }
  45. /**
  46. * @name:
  47. * @msg: 上传图片,图片必须是本地图片才可以上传成功
  48. * @param {string} $upload_url 上传路径
  49. * @param {string} $filename 本地图片路径
  50. * @param {array} $headers
  51. * @return {*}
  52. */
  53. public static function upload(string $upload_url, string $filename = '', array $headers = [])
  54. {
  55. if (!empty($headers)) {
  56. $headers = array_merge(['Content-Type' => 'multipart/form-data'], $headers);
  57. } else {
  58. $headers = ['Content-Type' => 'multipart/form-data'];
  59. }
  60. $img_str = file_get_contents($filename);
  61. if (false === $img_str) throw new \Exception('文件不存在');
  62. $path = '/tmp/';
  63. if (!file_exists($path)) mkdir($path, 0755, true);
  64. $file_name = rtrim($path, '/') . '/' . pathinfo($filename, PATHINFO_BASENAME);
  65. file_put_contents($file_name, $img_str);
  66. $post_data = [
  67. "upload_type" => "images",
  68. //要上传的本地文件地址
  69. "file" => new \CURLFile($file_name)
  70. ];
  71. $header = [];
  72. foreach ($headers as $key => $val) {
  73. $header[] = $key . ':' . $val;
  74. }
  75. $ch = curl_init();
  76. curl_setopt($ch, CURLOPT_URL, $upload_url);
  77. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  78. curl_setopt($ch, CURLOPT_POST, 1);
  79. curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  80. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  81. $output = curl_exec($ch);
  82. curl_close($ch);
  83. $rst = json_decode($output, true);
  84. @unlink($file_name);
  85. return $rst;
  86. }
  87. public static function postFile(string $upload_url, array $params = [], array $headers = [])
  88. {
  89. // $file_path = $params['file_path'];
  90. // unset($params['file_path']);
  91. // $post_data = ["file" => new \CURLFile($file_path)];
  92. // $post_data = array_merge($post_data,$params);
  93. $ch = curl_init();
  94. curl_setopt($ch, CURLOPT_URL, $upload_url);
  95. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  96. curl_setopt($ch, CURLOPT_POST, 1);
  97. curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
  98. $output = curl_exec($ch);
  99. curl_close($ch);
  100. return json_decode($output, true);
  101. }
  102. private static function request(string $url, string $method = 'get', array $params = [], array $headers = [], string $format = 'json')
  103. {
  104. $client = new Client(self::$config);
  105. if ('get' == $method) {
  106. $response = $client->request($method, $url, ['headers' => $headers,'timeout'=>20]);
  107. } else {
  108. $response = $client->request($method, $url, [$format => $params, 'headers' => $headers]);
  109. }
  110. $status_code = $response->getStatusCode();
  111. if (200 != $status_code) {
  112. throw new \Exception('网络请求错误, http code: ' . $status_code . ', reason: ' . $response->getReasonPhrase());
  113. }
  114. $rst = json_decode($response->getBody()->getContents(), true);
  115. return $rst;
  116. }
  117. //下载文件
  118. public static function downImgRar($url, $file_name, $ext,$absolute_dir)
  119. {
  120. if (!is_dir($absolute_dir)) {
  121. mkdir($absolute_dir, 0777, true);
  122. }
  123. $ch = curl_init($url);
  124. curl_setopt($ch, CURLOPT_HEADER, 0);
  125. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  126. curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
  127. $rawdata = curl_exec($ch);
  128. curl_close($ch);
  129. // 使用中文文件名需要转码
  130. $fp = fopen($absolute_dir . iconv('UTF-8', 'GBK', $file_name) . "." . $ext, 'w');
  131. fwrite($fp, $rawdata);
  132. fclose($fp);
  133. // 返回路径
  134. return $absolute_dir . $file_name . "." . $ext;
  135. }
  136. /**
  137. * post
  138. *
  139. * @param string $url
  140. * @param array $params
  141. * @param array $headers
  142. * @return string
  143. */
  144. public static function postJson(string $url, array $params = [], array $headers = [])
  145. {
  146. $http = new Client(['headers' => [
  147. "Content-type" => 'application/json'
  148. ]]);
  149. $response = $http->post($url, [
  150. 'form_params' => $params
  151. ]);
  152. //返回值
  153. $result = $response->getBody()->getContents();
  154. return Json::decode($result);
  155. }
  156. public static function postJsonUnicode(string $url, array $params = [], array $headers = []){
  157. $post_data = json_encode($params,JSON_UNESCAPED_UNICODE);
  158. $ch = curl_init();
  159. curl_setopt ($ch, CURLOPT_URL, $url);
  160. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  161. curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
  162. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  163. $headers = array_merge($headers,[
  164. 'Content-Type: application/json',
  165. 'Content-Length: ' . strlen($post_data)
  166. ]);
  167. curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
  168. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这里的意思是请求https
  169. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//这里的意思是请求https
  170. $res = curl_exec($ch);
  171. $res = json_decode($res,true);//转成数组
  172. curl_close($ch);
  173. return $res;
  174. }
  175. public static function postV2(string $url, array $params = [], array $headers = []){
  176. $post_data = json_encode($params,JSON_UNESCAPED_UNICODE);
  177. $ch = curl_init();
  178. curl_setopt ($ch, CURLOPT_URL, $url);
  179. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
  180. curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
  181. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  182. $newHeaders = [];
  183. foreach ($headers as $k => $v) {
  184. $newHeaders[] = sprintf('%s: %s', $k, $v);
  185. }
  186. curl_setopt($ch, CURLOPT_HTTPHEADER, $newHeaders);
  187. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这里的意思是请求https
  188. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);//这里的意思是请求https
  189. $res = curl_exec($ch);
  190. $sourceData = $res;
  191. $res = json_decode($res,true);//转成数组
  192. curl_close($ch);
  193. return is_array($res) ? $res : $sourceData;
  194. }
  195. public static function setConfig(array $config)
  196. {
  197. self::$config = $config;
  198. }
  199. }