PageRenderTime 163ms CodeModel.GetById 81ms app.highlight 3ms RepoModel.GetById 77ms app.codeStats 0ms

/lib/curl_response.php

https://github.com/dimon36/projekt_1
PHP | 83 lines | 27 code | 11 blank | 45 comment | 1 complexity | 810d29ef27780df1a4db408eaf9af842 MD5 | raw file
 1<?php
 2
 3/**
 4 * Parses the response from a Curl request into an object containing
 5 * the response body and an associative array of headers
 6 *
 7 * @package curl
 8 * @author Sean Huber <shuber@huberry.com>
 9**/
10class CurlResponse {
11    
12    /**
13     * The body of the response without the headers block
14     *
15     * @var string
16    **/
17    public $body = '';
18    
19    /**
20     * An associative array containing the response's headers
21     *
22     * @var array
23    **/
24    public $headers = array();
25    
26    /**
27     * Accepts the result of a curl request as a string
28     *
29     * <code>
30     * $response = new CurlResponse(curl_exec($curl_handle));
31     * echo $response->body;
32     * echo $response->headers['Status'];
33     * </code>
34     *
35     * @param string $response
36    **/
37    function __construct($response) {
38        # Headers regex
39        $pattern = '#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims';
40        
41        # Extract headers from response
42        preg_match_all($pattern, $response, $matches);
43        $headers_string = array_pop($matches[0]);
44        $headers = explode("\r\n", str_replace("\r\n\r\n", '', $headers_string));
45        
46        # Inlude all received headers in the $headers_string
47        while (count($matches[0])) {
48          $headers_string = array_pop($matches[0]).$headers_string;
49        }
50
51        # Remove all headers from the response body
52        $this->body = str_replace($headers_string, '', $response);
53        
54        # Extract the version and status from the first header
55        $version_and_status = array_shift($headers);
56        preg_match('#HTTP/(\d\.\d)\s(\d\d\d)\s(.*)#', $version_and_status, $matches);
57        $this->headers['Http-Version'] = $matches[1];
58        $this->headers['Status-Code'] = $matches[2];
59        $this->headers['Status'] = $matches[2].' '.$matches[3];
60        
61        # Convert headers into an associative array
62        foreach ($headers as $header) {
63            preg_match('#(.*?)\:\s(.*)#', $header, $matches);
64            $this->headers[$matches[1]] = $matches[2];
65        }
66    }
67    
68    /**
69     * Returns the response body
70     *
71     * <code>
72     * $curl = new Curl;
73     * $response = $curl->get('google.com');
74     * echo $response;  # => echo $response->body;
75     * </code>
76     *
77     * @return string
78    **/
79    function __toString() {
80        return $this->body;
81    }
82    
83}