Форум программистов, компьютерный форум, киберфорум
PHP для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.56/9: Рейтинг темы: голосов - 9, средняя оценка - 4.56
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44

Парсер для API GitHub

14.05.2016, 14:33. Показов 1982. Ответов 20
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Народ нужна помощь такого рода:

Есть например страница GitHub-a с текстом: https://api.github.com/users/Gamblt

2 дня уже мучаюсь, и немогу ету инфу скопировавь....

Нужно как то ету инфу скопировать и хотя бы вывести на своей странице - как такое можно сделать?
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
14.05.2016, 14:33
Ответы с готовыми решениями:

Добавить в парсер тег из xml для передачи по api
Есть файл xml (стандартный экспорт заказов из prom.ua, tiu.ru) и модуль, который представляет собой обычный парсер. Он разбирает xml и...

Какую python3-библиотеку для работы с github api Вы посоветуете?
Доброго дня, уважаемые гуру. хочу написать небольшое приложение на python, для построения расширенного рейтинга репозиториев на github. На...

API Github
Всем привет, подскажите библиотеки для работы(загрузка, удаление) файлов в репозитории. Ну, желательно бы и ссылку на статью, где есть...

20
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 14:42
Лучший ответ Сообщение было отмечено ExtremeCat как решение

Решение

PHP
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
<?php
 
@header('Content-Type: text/html; charset=utf-8');
 
class Common_Misc {
    protected function prepare_name( $name ) {
        return strtolower(trim($name));
    }
}
class Cookie_Item {
    public function __construct( $name = null , $value = null , $expire = 0 , $path = null , $domain = null , $secure = false , $httponly = false ) {
        $this->name = $name;
        $this->value = $value;
        $this->expire = $expire;
        $this->path = $path;
        $this->domain = $domain;
        $this->secure = $secure;
        $this->httponly = $httponly;
    }
    public function Serialize() {
        return serialize( (Array) $this );
    }
    public static function Unserialize( $str ) {
        if ( !($a = @unserialize($str)) ) {
            return null;
        }
        $r = new self();
        $r->Change( $a );
        return $r;
    }
    public $name;
    public $value;
    public $expire;
    public $path;
    public $domain;
    public $secure;
    public $httponly;
}
class Cookie_List extends Common_Misc {
    public $change_enabled = true;
    private $cookie_list = [];
    public function Set( Cookie_Item $cookie ) {
        if ( !$this->change_enabled ) { return $this; }
        $name = $cookie->name;
        $name = $this->prepare_name( $name );
        unset($this->cookie_list[ $name ]);
        $this->cookie_list[ $name ] = $cookie;
        return $this;
    }
    public function Get( $name ) {
        $name = $this->prepare_name( $name );
        if ( isset($cookie_list[ $name ]) ) {
            return $cookie_list[ $name ];
        }
        return null;
    }
    public function Has( $name ) {
        $name = $this->prepare_name( $name );
        return isset($cookie_list[ $name ]);
    }
    public function Del( $name ) {
        if ( !$this->change_enabled ) { return $this; }
        $name = $this->prepare_name( $name );
        unset($cookie_list[ $name ]);
        return $this;
    }
    public function Change( $name , $attrKey , $attrVal = null ) {
        if ( !$this->change_enabled ) { return $this; }
        if ( is_array($attrKey) ) {
            foreach($attrKey as $k=>$v) {
                $this->Change( $name , $k , $v );
            }
            return;
        }
        if ( isset($cookie_list[ $name ]) ) {
            $cookie_list[ $name ]->{$attrKey} = $attrVal;
        }
        return $this;
    }
 
    public function ByCurlFile( $path , $clear = true ) {
        if ( !$this->change_enabled ) { return $this; }
        if ( !file_exists($path) )    { return $this; }
 
        if ( $clear ) {
            $this->cookie_list = [];
        }
        $lines = file( $path );
        
        foreach ($lines as $line) {
 
            $cookie = array();
 
            // detect httponly cookies and remove #HttpOnly prefix
            if (substr($line, 0, 10) == '#HttpOnly_') {
                $line = substr($line, 10);
                $cookie['httponly'] = true;
            } else {
                $cookie['httponly'] = false;
            } 
 
            // we only care for valid cookie def lines
            if($line[0] != '#' && substr_count($line, "\t") == 6) {
 
                // get tokens in an array
                $tokens = explode("\t", $line);
 
                // trim the tokens
                $tokens = array_map('trim', $tokens);
 
                // Extract the data
                $cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
                $cookie['flag'] = ($tokens[1] !== 'FALSE');   // A TRUE/FALSE value indicating if all machines within a given domain can access the variable. 
                $cookie['path'] = $tokens[2];   // The path within the domain that the variable is valid for.
                $cookie['secure'] = ($tokens[3] !== 'FALSE'); // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
 
                $cookie['expire'] = $tokens[4];  // The UNIX time that the variable will expire on.   
                $cookie['name'] = urldecode($tokens[5]);   // The name of the variable.
                $cookie['value'] = urldecode($tokens[6]);  // The value of the variable.
 
                $this->Set(
                    new Cookie_Item($cookie['name'] , $cookie['value'] , $cookie['expire'] , $cookie['path'] , $cookie['domain'] , $cookie['secure'] , $cookie['httponly'])
                );
            }
        }
        return $this;
    }
    public function ToCurlFile( $path ) {
        $s = "";
        $this->Each( function( $cookie ) use( &$s ) {
            $s .= 
                $cookie->domain . "\t" .
                'TRUE' . "\t" .
                $cookie->path . "\t" .
                ($cookie->secure?'TRUE':'FALSE') . "\t" .
                $cookie->expire . "\t" .
                $cookie->name . "\t" .
                $cookie->value . "\r\n";
        } );
        @file_put_contents( $path , $s );
        return $this;
    }
    
    public function Serialize() {
        $a = [];
        foreach($this->cookie_list as $c) {
            $a[] = $c->Serialize();
        }
        return serialize( $a );
    }
    public static function Unserialize( $str ) {
        if ( !($a = @unserialize($str)) ) {
            return null;
        }
        $r = new self();
        foreach($a as $c) {
            $r->Set( Cookie_Item::Unserialize( $c ) );
        }
        return $r;
    }
 
    public function Each( $f ) {
        foreach($this->cookie_list as $c) {
            $f( $c );
        }
        return $this;
    }
}
class Header {
    public $name;
    public $values;
    public function __construct( $name , $values ) {
        if ( !is_array($values) ) {
            $values = [$values];
        }
        $this->name = trim($name);
        foreach($values as &$v) {
            $v = trim($v);
        }
        $this->values = $values;
    }
    public function Add( $value ) {
        $this->values[] = trim($value);
    }
    public function ToString() {
        $result = "";
        foreach($this->values as $val) {
            $result .= trim( trim($this->name) . ": " . $this->prepare_value($val) ) . "\r\n";
        }
        return trim($result);
    }
    private function prepare_value( $value ) {
        return trim(str_replace( "\r\n" , "\r\n " , $value ));
    }
}
class Headers extends Common_Misc {
    public $head;
    public $headers = [];
    public function Set( Header $header ) {
        $this->headers[ $this->prepare_name( $header->name ) ] = $header;
        return $this;
    }
    public function Add( $name , $value ) {
        if ( $h = $this->Get( $name ) ) {
            $h->Add($value);
        } else {
            $this->Set( new Header( $name , $value ) );
        }
    }
    public function Get( $name ) {
        if ( isset($this->headers[ $name = $this->prepare_name( $name ) ]) ) {
            return $this->headers[ $name ];
        }
        return null;
    }
    public function Has( $name ) {
        return isset($this->headers[ $name = $this->prepare_name( $name ) ]);
    }
    public function Del( $name , $index = null ) {
        if  ( $index === null ) {
            unset( $this->headers[ $name = $this->prepare_name( $header->name ) ] );
        } elseif ( $h = $this->Get( $name ) ) {
            array_splice($h->values , $index , 1);
        }
        return $this;
    }
    public function ToString( $use_head = true ) {
        $result = "";
        if ( $this->head && $use_head ) {
            $result = $this->head . "\r\n";
        }
        $this->Each( function( $header ) use (&$result) {
            $result .= $header->ToString() . "\r\n";
        } );
        return $result;
    }
    public static function ByString( &$string ) {
        $_this = new self();
        if ( ($pos = strpos( $string , "\r\n\r\n" )) === false ) {
            return $_this;
        }
        $headers_string = substr($string , 0 , $pos + 2);
        $string = substr($string , $pos+4);
 
        do {
            $rand_s = substr(str_shuffle( "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789" ) , 0 , 32);
        } while( strpos($headers_string , $rand_s) !== false );
        
        $headers_string = str_replace( "\r\n " , $rand_s , $headers_string );
        $headers_string = str_replace( "\r\n\x09" , $rand_s , $headers_string );
        preg_match( "#([^\r\n:]*)\r\n#si" , $headers_string , $res );
        if ( !@$res[1] ) {
            return;
        }
        $_this->head = "";
        if ( strpos($res[1] , ":") !== false ) {
            $_this->head = trim( str_replace( $rand_s , "\r\n" , $res[1] ) );
        }
        
        preg_match_all( "#([^\r\n:]*):([^\r\n]*)\r\n#si" , $headers_string , $res );
        foreach($res[1] as $i=>$v) {
            $name = trim( str_replace( $rand_s , "\r\n" , $res[1][$i] ) );
            $value = trim( str_replace( $rand_s , "\r\n" , $res[2][$i] ) );
            $_this->Add( $name , $value );
        }
        return $_this;
    }
    public function Each( $f ) {
        foreach($this->headers as $header) {
            $f( $header );
        }
        return $this;
    }
    public function GetCurlArray() {
        $result = [];
        $this->Each( function( $header ) use (&$result) {
            $result[] = trim($header->ToString());
        } );
        return $result;
    }
 
    public function __construct() {
        foreach( func_get_args() as $arg ) {
            if ( !is_array($arg) ) {
                $arg = [$arg];
            }
            foreach($arg as $v) {
                $this->Set($v);
            }
        }
    }
}
class Curl_Return {
    public $error;
    public $info;
    public $headers;
    public $request_headers;
    public $content;
    public function __construct( $error , $content , $info ) {
        $this->error   = $error;
        $this->content = $content;
        $this->info    = $info;
        $this->headers = Headers::ByString( $this->content );
        $this->request_headers = Headers::ByString( $this->info['request_header'] );
    }
}
class Curl {
    public static function Get( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        $info = (Array)$info;
        $info["method"] = "get";
        return new self( $info , $headers , $cookie );
    }
    public static function Post( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        $info = (Array)$info;
        $info["method"] = "post";
        return new self( $info , $headers , $cookie );
    }
 
    private $curl;
    private $curl_multi;
    private $curl_active;
    
    public $url;
    public $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36';
    public $timeout = 10;
    public $connecttimeout = 3;
    public $method = 'get';
    public $fresh_connect = true;
    public $forbid_reuse = true;
    public $parameters = [];
 
    public $cookie_tmp_dir = "MTGNHQDDNPYLMMIWFYNQOYBNWEWHQSLV";
    private $cookie_tmp_file;
 
    private $attr_map = [ 
        'url' => CURLOPT_URL , 
        'useragent' => CURLOPT_USERAGENT , 
        'timeout' => CURLOPT_TIMEOUT , 
        'connecttimeout' => CURLOPT_CONNECTTIMEOUT ,
        'fresh_connect' => CURLOPT_FRESH_CONNECT ,
        'forbid_reuse' => CURLOPT_FORBID_REUSE
    ];
    public function __construct( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        if ( !is_dir( $this->cookie_tmp_dir ) ) {
            @mkdir($this->cookie_tmp_dir);
        }
 
        if ( $cookie === null  ) { $cookie = new Cookie_List(); }
        if ( $headers === null ) { $headers = new Headers(); }
        $this->cookie = $cookie;
        $this->headers = $headers;
        
        $this->Change( $info );
        return $this;
    }
    public function Change( $info = [] , $value2 = null ) {
        if ( $value2 !== null ) {
            $info = [ $info => $value2 ];
        }
        $info = (Array)$info;
        foreach($info as $k=>$v) {
            $this->{$k} = $v;
        }   
    }
 
    public function Load( $url = null ) {   
        $this->startLoad();
 
        if ( $url !== null ) {
            $this->url = $url;
        }
    
        $isPost = (strtolower(trim($this->method)) === "post");
 
        $options = Array(
            CURLOPT_POST => $isPost,
 
            CURLOPT_HEADER => 1, 
            CURLOPT_RETURNTRANSFER => 1,
            CURLINFO_HEADER_OUT => 1,
            CURLOPT_COOKIEFILE => $this->cookie_tmp_file,
            CURLOPT_COOKIEJAR => $this->cookie_tmp_file,
            CURLOPT_SSL_VERIFYPEER => 0
        );
        
        foreach($this->attr_map as $k=>$v) {
            $options[ $v ] = $this->{$k};
        }
        
        if ( $isPost ) {
            $options[ CURLOPT_POSTFIELDS ] = $this->parameters;
        }
 
        $options[ CURLOPT_HTTPHEADER ] = $this->headers->GetCurlArray();
        
        $this->curl_active = null;
        
        $this->curl = @curl_init();
        @curl_setopt_array( $this->curl , $options );
 
        $this->curl_multi = @curl_multi_init();
 
        @curl_multi_add_handle( $this->curl_multi , $this->curl );
        
        $this->IsLoad();
 
        return $this;
    }
    public function IsLoad() {
        $status = @curl_multi_exec( $this->curl_multi , $this->curl_active );
        $result = !($status === CURLM_CALL_MULTI_PERFORM || $this->curl_active);
        if ( $result ) {
            $this->result = new Curl_Return( @curl_error( $this->curl ) , @curl_multi_getcontent( $this->curl ) , @curl_getinfo( $this->curl ) );
            @curl_multi_remove_handle($this->curl_multi , $this->curl);
            @curl_close($this->curl);
            @curl_multi_close($this->curl_multi);
            $this->endLoad();
        }
        return $result;
    }
    public function Wait() {
        while( !$this->IsLoad() ) {
            usleep( $this->wait_time );
        }
        return $this;
    }
    private $wait_time = 100000;
    
    public $result;
    public $cookie;
    public $headers;
    
    private function startLoad() {
        $this->result = null;
        $this->cookie_tmp_file = tempnam($this->cookie_tmp_dir , "tmp");
        $this->cookie->ToCurlFile( $this->cookie_tmp_file );
    }
    private function endLoad() {
        $this->cookie->ByCurlFile( $this->cookie_tmp_file );
        unlink($this->cookie_tmp_file);
    }
}
 
$content = Curl::Get()->Load( 'https://api.github.com/users/Gamblt' )->Wait()->result->content;
echo "<pre>{$content}</pre>";
1
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 14:47  [ТС]
Вот такая вот ошыбка, но вроде же везде все зактыро что нужно...

Parse error: syntax error, unexpected '[' in O:\home\d.ua\www\rate.php on line 41
0
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 14:50
Лучший ответ Сообщение было отмечено ExtremeCat как решение

Решение

Цитата Сообщение от ExtremeCat Посмотреть сообщение
что нужно...
нужно php >= 5.4..x
щас сделаю

Добавлено через 2 минуты
http://pastebin.com/twUsgLSU

Добавлено через 18 секунд
php >= 5.3
1
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 15:08  [ТС]
спасибо большое!!!!! просто таки ОГРОМНОЕ СПАСИБО!!!!!
0
14.05.2016, 15:19

Не по теме:

WhiteMind, прошел по ссылке, увидел это

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static function Unserialize($str)
{
    if ($a = @unserialize($str)) {
        goto c0zs70;
    }
    goto c0zs10;
    c0zs70:
    goto c0zs11;
    c0zs10:
    return null;
    c0zs11:
    $r = new self();
    $r->Change($a);
    return $r;
}
и меня чуть не стошнило :D

0
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 15:21
Цитата Сообщение от Kerry_Jr Посмотреть сообщение
Не по теме:
WhiteMind, прошел по ссылке, увидел это

Не по теме:

ну просто 1е что пришло в голову чтобы не вручную не менять [] На array() это прогнать через обфускатор http://whitemind.freevar.com/

0
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 15:24  [ТС]
Не по теме: посоветуйте хорошые книги для изучения ПХП
0
Заблокирован
14.05.2016, 15:25
Ты просто все вопросы на форуме задавай, и не нужна книга.
0
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 15:26  [ТС]
просто я начинаю изучать пхп, нужно же с чего то начинать)
0
Эксперт PHP
 Аватар для Kerry_Jr
3106 / 2591 / 1219
Регистрация: 14.05.2014
Сообщений: 7,236
Записей в блоге: 1
14.05.2016, 15:33
ExtremeCat, выбирайте
1
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 15:35
Цитата Сообщение от Kerry_Jr Посмотреть сообщение
ExtremeCat, выбирайте

Не по теме:

думаю данную тему следует читать с конца . а то потом о5 будут темы с денвером и mysql_* функциями

2
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 15:56  [ТС]
всем пасибки)

Добавлено через 17 минут
еще такой вопросик: а как можно добраться до определенной строки из выводящегося текста?
0
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 15:59
Цитата Сообщение от ExtremeCat Посмотреть сообщение
еще такой вопросик: а как можно добраться до определенной строки из выводящегося текста?
до какой например
0
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 16:02  [ТС]
до каждой по отдельности - я просто пока не очень понимаю как они выводяться - толи как масив толи как ...
0
Эксперт PHP
 Аватар для Kerry_Jr
3106 / 2591 / 1219
Регистрация: 14.05.2014
Сообщений: 7,236
Записей в блоге: 1
14.05.2016, 16:04
Цитата Сообщение от ExtremeCat Посмотреть сообщение
из выводящегося текста?
Откуда и куда?
0
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 16:08  [ТС]
мне нужно взять некоторые значения с строк, присвоить их переменным и дальше что то с ними делать
0
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 16:13
PHP
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
<?php 
 
@header('Content-Type: text/html; charset=utf-8');
 
class Common_Misc {
    protected function prepare_name( $name ) {
        return strtolower(trim($name));
    }
}
class Cookie_Item {
    public function __construct( $name = null , $value = null , $expire = 0 , $path = null , $domain = null , $secure = false , $httponly = false ) {
        $this->name = $name;
        $this->value = $value;
        $this->expire = $expire;
        $this->path = $path;
        $this->domain = $domain;
        $this->secure = $secure;
        $this->httponly = $httponly;
    }
    public function Serialize() {
        return serialize( (Array) $this );
    }
    public static function Unserialize( $str ) {
        if ( !($a = @unserialize($str)) ) {
            return null;
        }
        $r = new self();
        $r->Change( $a );
        return $r;
    }
    public $name;
    public $value;
    public $expire;
    public $path;
    public $domain;
    public $secure;
    public $httponly;
}
class Cookie_List extends Common_Misc {
    public $change_enabled = true;
    private $cookie_list = [];
    public function Set( Cookie_Item $cookie ) {
        if ( !$this->change_enabled ) { return $this; }
        $name = $cookie->name;
        $name = $this->prepare_name( $name );
        unset($this->cookie_list[ $name ]);
        $this->cookie_list[ $name ] = $cookie;
        return $this;
    }
    public function Get( $name ) {
        $name = $this->prepare_name( $name );
        if ( isset($cookie_list[ $name ]) ) {
            return $cookie_list[ $name ];
        }
        return null;
    }
    public function Has( $name ) {
        $name = $this->prepare_name( $name );
        return isset($cookie_list[ $name ]);
    }
    public function Del( $name ) {
        if ( !$this->change_enabled ) { return $this; }
        $name = $this->prepare_name( $name );
        unset($cookie_list[ $name ]);
        return $this;
    }
    public function Change( $name , $attrKey , $attrVal = null ) {
        if ( !$this->change_enabled ) { return $this; }
        if ( is_array($attrKey) ) {
            foreach($attrKey as $k=>$v) {
                $this->Change( $name , $k , $v );
            }
            return;
        }
        if ( isset($cookie_list[ $name ]) ) {
            $cookie_list[ $name ]->{$attrKey} = $attrVal;
        }
        return $this;
    }
 
    public function ByCurlFile( $path , $clear = true ) {
        if ( !$this->change_enabled ) { return $this; }
        if ( !file_exists($path) )    { return $this; }
 
        if ( $clear ) {
            $this->cookie_list = [];
        }
        $lines = file( $path );
        
        foreach ($lines as $line) {
 
            $cookie = array();
 
            // detect httponly cookies and remove #HttpOnly prefix
            if (substr($line, 0, 10) == '#HttpOnly_') {
                $line = substr($line, 10);
                $cookie['httponly'] = true;
            } else {
                $cookie['httponly'] = false;
            } 
 
            // we only care for valid cookie def lines
            if($line[0] != '#' && substr_count($line, "\t") == 6) {
 
                // get tokens in an array
                $tokens = explode("\t", $line);
 
                // trim the tokens
                $tokens = array_map('trim', $tokens);
 
                // Extract the data
                $cookie['domain'] = $tokens[0]; // The domain that created AND can read the variable.
                $cookie['flag'] = ($tokens[1] !== 'FALSE');   // A TRUE/FALSE value indicating if all machines within a given domain can access the variable. 
                $cookie['path'] = $tokens[2];   // The path within the domain that the variable is valid for.
                $cookie['secure'] = ($tokens[3] !== 'FALSE'); // A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
 
                $cookie['expire'] = $tokens[4];  // The UNIX time that the variable will expire on.   
                $cookie['name'] = urldecode($tokens[5]);   // The name of the variable.
                $cookie['value'] = urldecode($tokens[6]);  // The value of the variable.
 
                $this->Set(
                    new Cookie_Item($cookie['name'] , $cookie['value'] , $cookie['expire'] , $cookie['path'] , $cookie['domain'] , $cookie['secure'] , $cookie['httponly'])
                );
            }
        }
        return $this;
    }
    public function ToCurlFile( $path ) {
        $s = "";
        $this->Each( function( $cookie ) use( &$s ) {
            $s .= 
                $cookie->domain . "\t" .
                'TRUE' . "\t" .
                $cookie->path . "\t" .
                ($cookie->secure?'TRUE':'FALSE') . "\t" .
                $cookie->expire . "\t" .
                $cookie->name . "\t" .
                $cookie->value . "\r\n";
        } );
        @file_put_contents( $path , $s );
        return $this;
    }
    
    public function Serialize() {
        $a = [];
        foreach($this->cookie_list as $c) {
            $a[] = $c->Serialize();
        }
        return serialize( $a );
    }
    public static function Unserialize( $str ) {
        if ( !($a = @unserialize($str)) ) {
            return null;
        }
        $r = new self();
        foreach($a as $c) {
            $r->Set( Cookie_Item::Unserialize( $c ) );
        }
        return $r;
    }
 
    public function Each( $f ) {
        foreach($this->cookie_list as $c) {
            $f( $c );
        }
        return $this;
    }
}
class Header {
    public $name;
    public $values;
    public function __construct( $name , $values ) {
        if ( !is_array($values) ) {
            $values = [$values];
        }
        $this->name = trim($name);
        foreach($values as &$v) {
            $v = trim($v);
        }
        $this->values = $values;
    }
    public function Add( $value ) {
        $this->values[] = trim($value);
    }
    public function ToString() {
        $result = "";
        foreach($this->values as $val) {
            $result .= trim( trim($this->name) . ": " . $this->prepare_value($val) ) . "\r\n";
        }
        return trim($result);
    }
    private function prepare_value( $value ) {
        return trim(str_replace( "\r\n" , "\r\n " , $value ));
    }
}
class Headers extends Common_Misc {
    public $head;
    public $headers = [];
    public function Set( Header $header ) {
        $this->headers[ $this->prepare_name( $header->name ) ] = $header;
        return $this;
    }
    public function Add( $name , $value ) {
        if ( $h = $this->Get( $name ) ) {
            $h->Add($value);
        } else {
            $this->Set( new Header( $name , $value ) );
        }
    }
    public function Get( $name ) {
        if ( isset($this->headers[ $name = $this->prepare_name( $name ) ]) ) {
            return $this->headers[ $name ];
        }
        return null;
    }
    public function Has( $name ) {
        return isset($this->headers[ $name = $this->prepare_name( $name ) ]);
    }
    public function Del( $name , $index = null ) {
        if  ( $index === null ) {
            unset( $this->headers[ $name = $this->prepare_name( $header->name ) ] );
        } elseif ( $h = $this->Get( $name ) ) {
            array_splice($h->values , $index , 1);
        }
        return $this;
    }
    public function ToString( $use_head = true ) {
        $result = "";
        if ( $this->head && $use_head ) {
            $result = $this->head . "\r\n";
        }
        $this->Each( function( $header ) use (&$result) {
            $result .= $header->ToString() . "\r\n";
        } );
        return $result;
    }
    public static function ByString( &$string ) {
        $_this = new self();
        if ( ($pos = strpos( $string , "\r\n\r\n" )) === false ) {
            return $_this;
        }
        $headers_string = substr($string , 0 , $pos + 2);
        $string = substr($string , $pos+4);
 
        do {
            $rand_s = substr(str_shuffle( "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789" ) , 0 , 32);
        } while( strpos($headers_string , $rand_s) !== false );
        
        $headers_string = str_replace( "\r\n " , $rand_s , $headers_string );
        $headers_string = str_replace( "\r\n\x09" , $rand_s , $headers_string );
        preg_match( "#([^\r\n:]*)\r\n#si" , $headers_string , $res );
        if ( !@$res[1] ) {
            return;
        }
        $_this->head = "";
        if ( strpos($res[1] , ":") !== false ) {
            $_this->head = trim( str_replace( $rand_s , "\r\n" , $res[1] ) );
        }
        
        preg_match_all( "#([^\r\n:]*):([^\r\n]*)\r\n#si" , $headers_string , $res );
        foreach($res[1] as $i=>$v) {
            $name = trim( str_replace( $rand_s , "\r\n" , $res[1][$i] ) );
            $value = trim( str_replace( $rand_s , "\r\n" , $res[2][$i] ) );
            $_this->Add( $name , $value );
        }
        return $_this;
    }
    public function Each( $f ) {
        foreach($this->headers as $header) {
            $f( $header );
        }
        return $this;
    }
    public function GetCurlArray() {
        $result = [];
        $this->Each( function( $header ) use (&$result) {
            $result[] = trim($header->ToString());
        } );
        return $result;
    }
 
    public function __construct() {
        foreach( func_get_args() as $arg ) {
            if ( !is_array($arg) ) {
                $arg = [$arg];
            }
            foreach($arg as $v) {
                $this->Set($v);
            }
        }
    }
}
class Curl_Return {
    public $error;
    public $info;
    public $headers;
    public $request_headers;
    public $content;
    public function __construct( $error , $content , $info ) {
        $this->error   = $error;
        $this->content = $content;
        $this->info    = $info;
        $this->headers = Headers::ByString( $this->content );
        $this->request_headers = Headers::ByString( $this->info['request_header'] );
    }
}
class Curl {
    public static function Get( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        $info = (Array)$info;
        $info["method"] = "get";
        return new self( $info , $headers , $cookie );
    }
    public static function Post( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        $info = (Array)$info;
        $info["method"] = "post";
        return new self( $info , $headers , $cookie );
    }
 
    private $curl;
    private $curl_multi;
    private $curl_active;
    
    public $url;
    public $useragent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36';
    public $timeout = 10;
    public $connecttimeout = 3;
    public $method = 'get';
    public $fresh_connect = true;
    public $forbid_reuse = true;
    public $parameters = [];
 
    public $cookie_tmp_dir = "MTGNHQDDNPYLMMIWFYNQOYBNWEWHQSLV";
    private $cookie_tmp_file;
 
    private $attr_map = [ 
        'url' => CURLOPT_URL , 
        'useragent' => CURLOPT_USERAGENT , 
        'timeout' => CURLOPT_TIMEOUT , 
        'connecttimeout' => CURLOPT_CONNECTTIMEOUT ,
        'fresh_connect' => CURLOPT_FRESH_CONNECT ,
        'forbid_reuse' => CURLOPT_FORBID_REUSE
    ];
    public function __construct( $info = [] , Headers $headers = null , Cookie_List $cookie = null ) {
        if ( !is_dir( $this->cookie_tmp_dir ) ) {
            @mkdir($this->cookie_tmp_dir);
        }
 
        if ( $cookie === null  ) { $cookie = new Cookie_List(); }
        if ( $headers === null ) { $headers = new Headers(); }
        $this->cookie = $cookie;
        $this->headers = $headers;
        
        $this->Change( $info );
        return $this;
    }
    public function Change( $info = [] , $value2 = null ) {
        if ( $value2 !== null ) {
            $info = [ $info => $value2 ];
        }
        $info = (Array)$info;
        foreach($info as $k=>$v) {
            $this->{$k} = $v;
        }   
    }
 
    public function Load( $url = null ) {   
        $this->startLoad();
 
        if ( $url !== null ) {
            $this->url = $url;
        }
    
        $isPost = (strtolower(trim($this->method)) === "post");
 
        $options = Array(
            CURLOPT_POST => $isPost,
 
            CURLOPT_HEADER => 1, 
            CURLOPT_RETURNTRANSFER => 1,
            CURLINFO_HEADER_OUT => 1,
            CURLOPT_COOKIEFILE => $this->cookie_tmp_file,
            CURLOPT_COOKIEJAR => $this->cookie_tmp_file,
            CURLOPT_SSL_VERIFYPEER => 0
        );
        
        foreach($this->attr_map as $k=>$v) {
            $options[ $v ] = $this->{$k};
        }
        
        if ( $isPost ) {
            $options[ CURLOPT_POSTFIELDS ] = $this->parameters;
        }
 
        $options[ CURLOPT_HTTPHEADER ] = $this->headers->GetCurlArray();
        
        $this->curl_active = null;
        
        $this->curl = @curl_init();
        @curl_setopt_array( $this->curl , $options );
 
        $this->curl_multi = @curl_multi_init();
 
        @curl_multi_add_handle( $this->curl_multi , $this->curl );
        
        $this->IsLoad();
 
        return $this;
    }
    public function IsLoad() {
        $status = @curl_multi_exec( $this->curl_multi , $this->curl_active );
        $result = !($status === CURLM_CALL_MULTI_PERFORM || $this->curl_active);
        if ( $result ) {
            $this->result = new Curl_Return( @curl_error( $this->curl ) , @curl_multi_getcontent( $this->curl ) , @curl_getinfo( $this->curl ) );
            @curl_multi_remove_handle($this->curl_multi , $this->curl);
            @curl_close($this->curl);
            @curl_multi_close($this->curl_multi);
            $this->endLoad();
        }
        return $result;
    }
    public function Wait() {
        while( !$this->IsLoad() ) {
            usleep( $this->wait_time );
        }
        return $this;
    }
    private $wait_time = 100000;
    
    public $result;
    public $cookie;
    public $headers;
    
    private function startLoad() {
        $this->result = null;
        $this->cookie_tmp_file = tempnam($this->cookie_tmp_dir , "tmp");
        $this->cookie->ToCurlFile( $this->cookie_tmp_file );
    }
    private function endLoad() {
        $this->cookie->ByCurlFile( $this->cookie_tmp_file );
        unlink($this->cookie_tmp_file);
    }
}
 
$content = Curl::Get()->Load( 'https://api.github.com/users/Gamblt' )->Wait()->result->content;
$content = json_decode($content);
 
$login = $content->login;
$id = $content->id;
$avatar_url = $content->avatar_url;
 
echo "<pre>";
    echo " login: $login \n id: $id \n avatar_url: $avatar_url \n";
echo "</pre>";
1
8 / 8 / 0
Регистрация: 28.02.2011
Сообщений: 44
14.05.2016, 16:18  [ТС]
а как вы переделываете с пхп 5,4 на 5.3 ?
0
Hello Kitty
 Аватар для WhiteMind
690 / 562 / 402
Регистрация: 12.02.2016
Сообщений: 1,436
Записей в блоге: 1
14.05.2016, 16:26
http://pastebin.com/JdSgDRML
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
14.05.2016, 16:26
Помогаю со студенческими работами здесь

GitHub API
Добрый день уважаемые форумчане, на протяжении многих лет черпал инфу с сего форума, и даже не нуждался в регистрации, так как искать...

Как обратится к API GitHub из программы С++
Я хочу сделать запрос https://api.github.com/users/Zhukovdpua/repos к API github из программы С++. Для работы с сетью использую winsock. ...

Как правильно использовать API github.com?
Как правильно использовать API github.com? Пробую получить информацию по токену с помощью запроса к API описанного по ссылке...

Работа с GitHub API в PHP, как сделать авторизацию ?
Суть задачи такая : пользователь авторизуется через OAuth2 в аккаунте GitHub и получает список своих репозиториев. Как сделать это на PHP +...

При запросе репозиториев пользователя GitHub API получить определенные поля
Подскажите, как при таком запросе https://api.github.com/users/PhilJay/repos получить только определенные поля, а не все. Например name и...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
Новые блоги и статьи
Модель сукцессии микоризы
anaschu 24.01.2026
Решили писать научную статью с неким РОманом
http://iceja.net/ математические сервисы
iceja 20.01.2026
Обновила свой сайт http:/ / iceja. net/ , приделала Fast Fourier Transform экстраполяцию сигналов. Однако предсказывает далеко не каждый сигнал (см ограничения http:/ / iceja. net/ fourier/ docs ). Также. . .
http://iceja.net/ сервер решения полиномов
iceja 18.01.2026
Выкатила http:/ / iceja. net/ сервер решения полиномов (находит действительные корни полиномов методом Штурма). На сайте документация по API, но скажу прямо VPS слабенький и 200 000 полиномов. . .
Расчёт переходных процессов в цепи постоянного тока
igorrr37 16.01.2026
/ * Дана цепь(не выше 3-го порядка) постоянного тока с элементами R, L, C, k(ключ), U, E, J. Программа находит переходные токи и напряжения на элементах схемы классическим методом(1 и 2 з-ны. . .
Восстановить юзерскрипты Greasemonkey из бэкапа браузера
damix 15.01.2026
Если восстановить из бэкапа профиль Firefox после переустановки винды, то список юзерскриптов в Greasemonkey будет пустым. Но восстановить их можно так. Для этого понадобится консольная утилита. . .
Сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru