1: | <?php
|
2: | |
3: | |
4: | |
5: | |
6: | |
7: | |
8: | |
9: | |
10: |
|
11: |
|
12: | |
13: | |
14: | |
15: | |
16: | |
17: | |
18: | |
19: | |
20: |
|
21: | class XoopsHttpGet
|
22: | {
|
23: | protected $useCurl = true;
|
24: | protected $url;
|
25: | protected $error;
|
26: |
|
27: | |
28: | |
29: | |
30: | |
31: | |
32: | |
33: |
|
34: | public function __construct($url)
|
35: | {
|
36: | $this->url = $url;
|
37: | if (!function_exists('curl_init')) {
|
38: | $this->useCurl = false;
|
39: | $urlFopen = (int) ini_get('allow_url_fopen');
|
40: | if ($urlFopen === 0) {
|
41: | throw new \RuntimeException("CURL extension or allow_url_fopen ini setting is required.");
|
42: | }
|
43: | }
|
44: | }
|
45: |
|
46: | |
47: | |
48: | |
49: | |
50: |
|
51: | public function fetch()
|
52: | {
|
53: | return ($this->useCurl) ? $this->fetchCurl() : $this->fetchFopen();
|
54: | }
|
55: |
|
56: | |
57: | |
58: | |
59: | |
60: |
|
61: | protected function fetchCurl()
|
62: | {
|
63: | $curlHandle = curl_init($this->url);
|
64: | if (false === $curlHandle) {
|
65: | $this->error = 'curl_init failed';
|
66: | return false;
|
67: | }
|
68: | $options = array(
|
69: | CURLOPT_RETURNTRANSFER => 1,
|
70: | CURLOPT_HEADER => 0,
|
71: | CURLOPT_CONNECTTIMEOUT => 10,
|
72: | CURLOPT_FOLLOWLOCATION => 1,
|
73: | CURLOPT_MAXREDIRS => 4,
|
74: | );
|
75: | curl_setopt_array($curlHandle, $options);
|
76: |
|
77: | $response = curl_exec($curlHandle);
|
78: | if (false === $response) {
|
79: | $this->error = curl_error($curlHandle);
|
80: | } else {
|
81: | $httpcode = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
|
82: | if (200 != $httpcode) {
|
83: | $this->error = $response;
|
84: | $response = false;
|
85: | }
|
86: | }
|
87: | curl_close($curlHandle);
|
88: | return $response;
|
89: | }
|
90: |
|
91: | |
92: | |
93: | |
94: | |
95: |
|
96: | protected function fetchFopen()
|
97: | {
|
98: | $response = file_get_contents($this->url);
|
99: | if (false === $response) {
|
100: | $this->error = 'file_get_contents() failed.';
|
101: | }
|
102: | return $response;
|
103: | }
|
104: |
|
105: | |
106: | |
107: | |
108: | |
109: |
|
110: | public function getError()
|
111: | {
|
112: | return $this->error;
|
113: | }
|
114: | }
|
115: | |