You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.6 KiB

  1. <?php
  2. namespace Telegraph;
  3. class HTTP {
  4. public static function get($url) {
  5. $ch = curl_init($url);
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  7. curl_setopt($ch, CURLOPT_HEADER, true);
  8. $response = curl_exec($ch);
  9. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  10. return array(
  11. 'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  12. 'headers' => self::_parse_headers(trim(substr($response, 0, $header_size))),
  13. 'body' => substr($response, $header_size)
  14. );
  15. }
  16. public static function post($url, $body, $headers=array()) {
  17. $ch = curl_init($url);
  18. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  19. curl_setopt($ch, CURLOPT_POST, true);
  20. curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
  21. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  22. curl_setopt($ch, CURLOPT_HEADER, true);
  23. if (self::$_proxy) curl_setopt($ch, CURLOPT_PROXY, self::$_proxy);
  24. $response = curl_exec($ch);
  25. self::_debug($response);
  26. $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
  27. return array(
  28. 'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  29. 'headers' => self::_parse_headers(trim(substr($response, 0, $header_size))),
  30. 'body' => substr($response, $header_size)
  31. );
  32. }
  33. public static function head($url) {
  34. $ch = curl_init($url);
  35. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  36. curl_setopt($ch, CURLOPT_HEADER, true);
  37. curl_setopt($ch, CURLOPT_NOBODY, true);
  38. if (self::$_proxy) curl_setopt($ch, CURLOPT_PROXY, self::$_proxy);
  39. $response = curl_exec($ch);
  40. return array(
  41. 'status' => curl_getinfo($ch, CURLINFO_HTTP_CODE),
  42. 'headers' => self::_parse_headers(trim($response)),
  43. );
  44. }
  45. public static function parse_headers($headers) {
  46. $retVal = array();
  47. $fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $headers));
  48. foreach($fields as $field) {
  49. if(preg_match('/([^:]+): (.+)/m', $field, $match)) {
  50. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  51. return strtoupper($m[0]);
  52. }, strtolower(trim($match[1])));
  53. // If there's already a value set for the header name being returned, turn it into an array and add the new value
  54. $match[1] = preg_replace_callback('/(?<=^|[\x09\x20\x2D])./', function($m) {
  55. return strtoupper($m[0]);
  56. }, strtolower(trim($match[1])));
  57. if(isset($retVal[$match[1]])) {
  58. if(!is_array($retVal[$match[1]]))
  59. $retVal[$match[1]] = array($retVal[$match[1]]);
  60. $retVal[$match[1]][] = $match[2];
  61. } else {
  62. $retVal[$match[1]] = trim($match[2]);
  63. }
  64. }
  65. }
  66. return $retVal;
  67. }
  68. }