CurlAdapter.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /**
  3. * TLDDatabase: Abstraction for Public Suffix List in PHP.
  4. *
  5. * @link https://github.com/layershifter/TLDDatabase
  6. *
  7. * @copyright Copyright (c) 2016, Alexander Fedyashov
  8. * @license https://raw.githubusercontent.com/layershifter/TLDDatabase/master/LICENSE Apache 2.0 License
  9. */
  10. namespace LayerShifter\TLDDatabase\Http;
  11. use LayerShifter\TLDDatabase\Exceptions\HttpException;
  12. /**
  13. * cURL adapter for fetching Public Suffix List.
  14. */
  15. final class CurlAdapter implements AdapterInterface
  16. {
  17. /**
  18. * @const int Number of seconds for HTTP timeout.
  19. */
  20. const TIMEOUT = 60;
  21. /**
  22. * @inheritdoc
  23. */
  24. public function get($url)
  25. {
  26. $curl = curl_init();
  27. curl_setopt($curl, CURLOPT_URL, $url);
  28. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
  29. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  30. curl_setopt($curl, CURLOPT_TIMEOUT, CurlAdapter::TIMEOUT);
  31. curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, CurlAdapter::TIMEOUT);
  32. // If windows is used, SSL verification will be disabled.
  33. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  34. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  35. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  36. }
  37. $responseContent = curl_exec($curl);
  38. $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  39. $errorMessage = curl_error($curl);
  40. $errorNumber = curl_errno($curl);
  41. curl_close($curl);
  42. if ($errorNumber !== 0) {
  43. throw new HttpException(sprintf('Get cURL error while fetching PSL file: %s', $errorMessage));
  44. }
  45. if ($responseCode !== 200) {
  46. throw new HttpException(
  47. sprintf('Get invalid HTTP response code "%d" while fetching PSL file', $responseCode)
  48. );
  49. }
  50. return preg_split('/[\n\r]+/', $responseContent);
  51. }
  52. }