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