Curl.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Components;
  3. class Curl
  4. {
  5. /**
  6. * @param string $url 请求地址
  7. * @param array $data 数据,如果有数据则用POST请求
  8. *
  9. * @return mixed
  10. */
  11. public static function send($url, $data = [])
  12. {
  13. $ch = curl_init();
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  15. curl_setopt($ch, CURLOPT_TIMEOUT, 3);
  16. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  17. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  18. curl_setopt($ch, CURLOPT_URL, $url);
  19. if ($data) {
  20. curl_setopt($ch, CURLOPT_POST, 1);
  21. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  22. }
  23. $res = curl_exec($ch);
  24. curl_close($ch);
  25. return $res;
  26. }
  27. /**
  28. * POST JSON数据
  29. *
  30. * @param string $url 请求地址
  31. * @param string $data JSON数据
  32. * @param string $secret 通信密钥
  33. *
  34. * @return mixed
  35. */
  36. public static function sendJson($url, $data, $secret)
  37. {
  38. $header = [
  39. 'Content-Type: application/json; charset=utf-8',
  40. 'Content-Length: ' . strlen($data),
  41. 'Secret: ' . $secret
  42. ];
  43. $ch = curl_init();
  44. curl_setopt($ch, CURLOPT_URL, $url);
  45. curl_setopt($ch, CURLOPT_POST, true);
  46. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  47. curl_setopt($ch, CURLOPT_TIMEOUT, 3);
  48. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  49. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  50. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  51. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  52. $res = curl_exec($ch);
  53. curl_close($ch);
  54. return json_decode($res);
  55. }
  56. }