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.

75 lines
2.7 KiB

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