My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<?
/**
* HTTP Class
*
* Позволяет легко выполнять GET и POST запросы, хранить
* и устанавливать cookies, следовать редиректам и
* возвращать данные в необходимой кодировке. Так же имеется
* встроенная функция для исправления относительных ссылок
* в абсолютные.
*
* @author Jeck (http://jeck.ru)
*/
class http {
public $user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 (.NET CLR 3.5.30729)';

public $cookies = array();
public $referer = '';
public $timeout = 10;

public $externalIp;

public $proxy = '';
public $proxy_type = CURLPROXY_HTTP;

public $current_url;

// Режим следования по редиректу (true - включен, false - выключен)
public $follow_location = true;

// Кодировка по умолчанию
public $default_encoding = 'WINDOWS-1251';

// Кодировка страницы
public $encoding = '';

public $info;

private $ch;
private $result;
private $result_headers;
private $result_body;
private $location = '';

public function get($url, $encoding=null) {
$this->init($url);
$this->setDefaults();
$this->exec();

if ($this->follow_location && !empty($this->location)) {
return $this->get(self::fixUrl($url,$this->location), $encoding);
} else {
return $this->processEncoding($this->result_body, $encoding);
}
}

public function post($url, $postdata, $encoding=null) {
$this->init($url);
$this->setPostFields($postdata);
$this->setDefaults();
$this->exec();

if ($this->follow_location && !empty($this->location)) {
return $this->get(self::fixUrl($url, $this->location), $encoding);
} else {
return $this->processEncoding($this->result_body, $encoding);
}
}

/**
Возвращает заголовки последнего запроса
*/
public function getHeaders() {
return $this->result_headers;
}

/**
Выполняет начальную инициализацию запроса
*/
private function init($url) {
$this->current_url = $url;
$this->ch = curl_init($url);

// Если запрос с использованием SSL - отключаем проверку сертификата
$scheme = parse_url($url,PHP_URL_SCHEME);
$scheme = strtolower($scheme);
if ($scheme == 'https') {
curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, false);
}
}

/**
Запускает обработку запроса
*/
private function exec() {
// Установливает параметры необходимые для правильной обработки данных
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->ch, CURLOPT_HEADER, true);

// Выполняем запрос и получаем информацию
$this->result = curl_exec($this->ch);
$this->info = curl_getinfo($this->ch);

$this->processHeaders();
$this->processBody();
$this->correctEncoding();
}

/**
Получает заголовки запроса и обрабатывает их содержимое
*/
private function processHeaders() {
$this->location = '';
$this->referer = $this->info['url'];
$this->result_headers = substr($this->result,0,$this->info['header_size']);
$headers = explode("\r\n",$this->result_headers);
foreach ($headers as $header) {
if (strpos($header,":") !== false) {
list($key,$value) = explode(":",$header,2);
$key = trim($key);
$key = strtolower($key);
switch ($key) {
case 'set-cookie':
$this->processSetCookie($value);
break;
case 'content-type':
$this->processContentType($value);
break;
case 'location':
$this->processLocation($value);
break;
}
}
}
}

/**
Обрабатывает заголовок set-cookie
*/
private function processSetCookie($string) {
$parts = explode(';', $string);
$domain = '.';
$cookies = array();
$expires = false;
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part, 2);
$key = trim($key);
$value = trim($value);
} else {
$key = trim($part);
$value = '';
}
if (strtolower($key) == 'domain') {
$domain = $value;
}
if (strtolower($key) == 'expires') {
if ($time = strtotime($value)) {
$expires = (boolean) time() > $time;
}
}
if (!in_array(strtolower($key), array('domain', 'expires', 'path', 'secure', 'comment'))) {
$cookies[$key] = $value;
}
}
foreach ($cookies as $key => $value) {
if ($expires) {
unset($this->cookies[$domain][$key]);
} else {
$this->cookies[$domain][$key] = $value;
}
}
}

/**
Обрабатывает заголовок content-type
*/
private function processContentType($string) {
$pos = strpos($string,'charset');
if ($pos !== false) {
$endpos = strpos($string,';',$pos);
if ($endpos === false) {
$charset = substr($string,$pos);
} else {
$length = $endpos - $pos;
$charset = substr($string,$pos,$length);
}
list(,$this->encoding) = explode("=",$charset,2);
}
}

/**
Обрабатывает заголовок location
*/
private function processLocation($string) {
$this->location = trim($string);
}

/**
Получает тело страницы
*/
private function processBody() {
$this->result_body = substr($this->result,$this->info['header_size']);
// Определяем кодировку по meta тегам
if (is_null($this->encoding)) {
if (preg_match("#<meta\b[^<>]*?\bcontent=['\"]?text/html;\s*charset=([^>\s\"']+)['\"]?#is", $this->result_body, $match)) {
$this->encoding = strtoupper($match[1]);
}
}
}

/**
Возвращает тело страницы в нужной кодировке
*/
private function processEncoding($body,$encoding) {
if ($encoding !== null && !empty($this->encoding)) {
return iconv($this->encoding, $encoding.'//TRANSLIT', $body);
}
return $body;
}

/**
Устанавливает начальные параметры заданные в свойствах
*/
private function setDefaults() {
$this->encoding = null;
$this->setUserAgent();
$this->setReferer();
$this->setCookies();
$this->setProxy();
$this->setTimeout();
$this->setExternalIp();
}

/**
Устанавливает UserAgent для curl
*/
private function setUserAgent() {
if (!empty($this->user_agent)) {
curl_setopt($this->ch, CURLOPT_USERAGENT, $this->user_agent);
}
}

/**
Устанавливает Referer для curl
*/
private function setReferer() {
if (!empty($this->referer)) {
curl_setopt($this->ch, CURLOPT_REFERER, $this->referer);
}
}

/**
Преобразуем cookies в строку и устанавливаем их для curl
*/
private function setCookies() {
if (is_array($this->cookies)) {
$cookie_string = '';
$currentHost = parse_url($this->current_url, PHP_URL_HOST);
foreach ($this->cookies as $cookieDomain => $cookies) {
if ($currentHost{0} !== '.') {
$currentHost = '.'.$currentHost;
}
if ($cookieDomain == '.' || preg_match('/'.preg_quote($cookieDomain, '/').'$/i', $currentHost)) {
foreach ($cookies as $key => $value) {
$cookie_string .= $key.'='.$value.'; ';
}
}
}
if (strlen($cookie_string) > 0) {
$cookie_string = substr($cookie_string, 0, -2);
curl_setopt($this->ch, CURLOPT_COOKIE, $cookie_string);
}
}
}

/**
Преобразуем postdata в строку и устанавливаем в качестве post_fields
*/
private function setPostFields($postdata) {
curl_setopt($this->ch, CURLOPT_POST, true);
curl_setopt($this->ch, CURLOPT_POSTFIELDS, http_build_query($postdata, '', '&'));
}

/**
Устанавливаем proxy если необходимо
*/
private function setProxy() {
if (!empty($this->proxy)) {
curl_setopt($this->ch, CURLOPT_PROXY, $this->proxy);
curl_setopt($this->ch, CURLOPT_PROXYTYPE, $this->proxy_type);
}
}

/**
Устанавливает таймаут соединения
*/
private function setTimeout() {
if ($this->timeout > 0) {
curl_setopt($this->ch, CURLOPT_TIMEOUT, $this->timeout);
}
}
/**
Устанавливает внешний IP интерфейс
*/
private function setExternalIp() {
if (!is_null($this->externalIp)) {
curl_setopt($this->ch, CURLOPT_INTERFACE, $this->externalIp);
}
}

/**
Корректирует кодировку если она задана в виде не подходящим для curl
*/
private function correctEncoding() {
if (!is_null($this->encoding)) {
if (preg_match('/\d{4}$/i', $this->encoding, $match)) {
$this->encoding = 'WINDOWS-'.$match[0];
}
$this->encoding = strtoupper($this->encoding);
} else {
$this->encoding = $this->default_encoding;
}
}

/**
Преобразовывает относительные URL в абсолютные по базе
*/
final static function fixUrl($baseUrl, $url) {
$baseParts = parse_url($baseUrl);
if (preg_match('/^\/\//', $url)) {
$url = $baseParts['scheme'].':'.$url;
}
$urlParts = parse_url($url);
if (isset($urlParts['scheme'])) {
return self::buidUrl($urlParts);
}
$parts = $baseParts;
if (!isset($baseParts['path'])) {
$baseParts['path'] = '';
}
unset($parts['fragment']);
if (isset($urlParts['path'])) {
unset($parts['query']);
if (strpos($urlParts['path'], '/') === 0) {
$parts['path'] = $urlParts['path'];
} else if (isset($urlParts['path']) && !empty($urlParts['path'])) {
$basePath = explode('/', $baseParts['path']);
array_pop($basePath);
$urlPath = explode('/', $urlParts['path']);
$lastSegment = count($urlPath) - 1;
foreach ($urlPath as $key => $pathSegment) {
if ($pathSegment == '.') {
continue;
} else if ($pathSegment == '..') {
if (count($basePath) > 0) {
array_pop($basePath);
}
} else if (empty($pathSegment) && $key != $lastSegment) {
$basePath = array();
} else {
array_push($basePath, $pathSegment);
}
}
$basePath = implode('/', $basePath);
if (strpos($basePath, '/') !== 0) {
$basePath = '/'.$basePath;
}
$parts['path'] = $basePath;
}
}
if (isset($urlParts['query'])) {
$parts['query'] = $urlParts['query'];
}
if (isset($urlParts['fragment'])) {
$parts['fragment'] = $urlParts['fragment'];
}
return self::buidUrl($parts);
}

final static function buidUrl($parts) {
$url = (isset($parts['scheme']) ? $parts['scheme'].'://' : 'http://').
(isset($parts['user']) ? $parts['user'].(isset($parts['pass']) ? ':' . $parts['pass'] : '') .'@' : '').
(isset($parts['host']) ? $parts['host'] : '').
(isset($parts['port']) ? ':' . $parts['port'] : '').
(isset($parts['path']) ? $parts['path'] : '/').
(isset($parts['query']) ? '?' . $parts['query'] : '').
(isset($parts['fragment']) ? '#' . $parts['fragment'] : '');
return $url;
}
}

?>

Change log

r9 by Jeck.ru on Jan 31, 2011   Diff
Исправлен метод setCookies работающий
неправильно в некоторых случаях
Go to: 
Project members, sign in to write a code review

Older revisions

r8 by Jeck.ru on Jan 31, 2011   Diff
Фикс обработки postdata в
http_build_query
r7 by Jeck.ru on Nov 21, 2010   Diff
Добавлен метод для коррекции кодировки
страницы
r6 by Jeck.ru on Nov 10, 2010   Diff
Добавлен метод getHeaders для
получения заголовков последнего
запроса
All revisions of this file

File info

Size: 11749 bytes, 393 lines
Powered by Google Project Hosting