You are here

12 March 2018

Handles any HTTP request correctly. This is a flexible and powerful HTTP client implementation of GET, POST, PUT or any other HTTP requests. The reason I built this was due to use of url arguments without any attributes in a specific feed url. Both curl and get_file_contents methods failed.

Source code viewer
  1. /**
  2.  * Request class that works with requests as well as a web browser.
  3.  *
  4.  * @param string $url: A string containing a fully qualified URI.
  5.  *
  6.  * @param array $options: (optional) An array that can have one or more of the following elements:
  7.  * headers: An array containing request headers to send as name/value pairs.
  8.  * method: A string containing the request method. Defaults to 'GET'.
  9.  * data: A string containing the request body, formatted as
  10.  * 'param=value&param=value&...'; to generate this, use http_build_query().
  11.  * Defaults to NULL.
  12.  * max_redirects: An integer representing how many times a redirect
  13.  * may be followed. Defaults to 3.
  14.  * timeout: A float representing the maximum number of seconds the function
  15.  * call may take. The default is 30 seconds. If a timeout occurs, the error
  16.  * code is set to -1.
  17.  * context: A context resource created with stream_context_create().
  18.  *
  19.  *
  20.  * @return object
  21.  * An object that can have one or more of the following components:
  22.  * request: A string containing the request body that was sent.
  23.  * code: An integer containing the response status code, or the error code
  24.  * if an error occurred.
  25.  * protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
  26.  * status_message: The status message from the response, if a response was
  27.  * received.
  28.  * redirect_code: If redirected, an integer containing the initial response
  29.  * status code.
  30.  * redirect_url: If redirected, a string containing the URL of the redirect
  31.  * target.
  32.  * error: If an error occurred, the error message. Otherwise not set.<
  33.  * headers: An array containing the response headers as name/value pairs.
  34.  * HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
  35.  * easy access the array keys are returned in lower case.
  36.  * data: A string containing the response body that was received.
  37.  *
  38.  *
  39.  * Standalone version of drupal_http_request from Drupal 7.
  40.  * @see https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_http_request/7.x
  41.  * @licence GNU General Public Licence see LICENCE file or http://www.gnu.org/licenses/gpl.html
  42.  */
  43. function request($url, array $options = array()) {
  44. $timer = array('start' => microtime(TRUE));
  45. $result = new stdClass();
  46.  
  47. // Parse the URL and make sure we can handle the schema.
  48. $uri = @parse_url($url);
  49. if ($uri == FALSE) {
  50. $result->error = 'unable to parse URL';
  51. $result->code = -1001;
  52. return $result;
  53. }
  54. if (!isset($uri['scheme'])) {
  55. $result->error = 'missing schema';
  56. $result->code = -1002;
  57. return $result;
  58. }
  59.  
  60. // Merge the default options.
  61. $options += array(
  62. 'headers' => array(),
  63. 'method' => 'GET',
  64. 'data' => NULL,
  65. 'max_redirects' => 3,
  66. 'timeout' => 30.0,
  67. 'context' => NULL,
  68. );
  69.  
  70. // Merge the default headers.
  71. $options['headers'] += array(
  72. 'User-Agent' => 'Drupal (+http://drupal.org/)',
  73. );
  74.  
  75. // stream_socket_client() requires timeout to be a float.
  76. $options['timeout'] = (double) $options['timeout'];
  77.  
  78. switch ($uri['scheme']) {
  79. case 'http':
  80. $port = isset($uri['port']) ? $uri['port'] : 80;
  81. $socket = 'tcp://' . $uri['host'] . ':' . $port;
  82.  
  83. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  84. // We don't add the standard port to prevent from breaking rewrite rules
  85. // checking the host that do not take into account the port number.
  86. if (!isset($options['headers']['Host'])) {
  87. $options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
  88. }
  89. break;
  90. case 'https':
  91.  
  92. // Note: Only works when PHP is compiled with OpenSSL support.
  93. $port = isset($uri['port']) ? $uri['port'] : 443;
  94. $socket = 'ssl://' . $uri['host'] . ':' . $port;
  95. if (!isset($options['headers']['Host'])) {
  96. $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
  97. }
  98. break;
  99. default:
  100. $result->error = 'invalid schema ' . $uri['scheme'];
  101. $result->code = -1003;
  102. return $result;
  103. }
  104. if (empty($options['context'])) {
  105. $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
  106. }
  107. else {
  108.  
  109. // Create a stream with context. Allows verification of a SSL certificate.
  110. $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
  111. }
  112.  
  113. // Make sure the socket opened properly.
  114. if (!$fp) {
  115.  
  116. // When a network error occurs, we use a negative number so it does not
  117. // clash with the HTTP status codes.
  118. $result->code = -$errno;
  119. $result->error = trim($errstr) ? trim($errstr) : 'Error opening socket ' . $socket;
  120.  
  121. return $result;
  122. }
  123.  
  124. // Construct the path to act on.
  125. $path = isset($uri['path']) ? $uri['path'] : '/';
  126. if (isset($uri['query'])) {
  127. $path .= '?' . $uri['query'];
  128. }
  129.  
  130. // Only add Content-Length if we actually have any content or if it is a POST
  131. // or PUT request. Some non-standard servers get confused by Content-Length in
  132. // at least HEAD/GET requests, and Squid always requires Content-Length in
  133. // POST/PUT requests.
  134. $content_length = strlen($options['data']);
  135. if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
  136. $options['headers']['Content-Length'] = $content_length;
  137. }
  138.  
  139. // If the server URL has a user then attempt to use basic authentication.
  140. if (isset($uri['user'])) {
  141. $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
  142. }
  143.  
  144. $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
  145. foreach ($options['headers'] as $name => $value) {
  146. $request .= $name . ': ' . trim($value) . "\r\n";
  147. }
  148. $request .= "\r\n" . $options['data'];
  149. $result->request = $request;
  150.  
  151. // Calculate how much time is left of the original timeout value.
  152. $stop = microtime(TRUE);
  153. $diff = round(($stop - $timer['start']) * 1000, 2);
  154. if (isset($timer['time'])) {
  155. $diff += $timer['time'];
  156. }
  157. $timeout = $options['timeout'] - $diff / 1000;
  158. if ($timeout > 0) {
  159. stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
  160. fwrite($fp, $request);
  161. }
  162.  
  163. // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
  164. // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
  165. // instead must invoke stream_get_meta_data() each iteration.
  166. $info = stream_get_meta_data($fp);
  167. $alive = !$info['eof'] && !$info['timed_out'];
  168. $response = '';
  169. while ($alive) {
  170. // Calculate how much time is left of the original timeout value.
  171. $stop = microtime(TRUE);
  172. $diff = round(($stop - $timer['start']) * 1000, 2);
  173. if (isset($timer['time'])) {
  174. $diff += $timer['time'];
  175. }
  176. $timeout = $options['timeout'] - $diff / 1000;
  177. if ($timeout <= 0) {
  178. $info['timed_out'] = TRUE;
  179. break;
  180. }
  181. stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
  182. $chunk = fread($fp, 1024);
  183. $response .= $chunk;
  184. $info = stream_get_meta_data($fp);
  185. $alive = !$info['eof'] && !$info['timed_out'] && $chunk;
  186. }
  187. fclose($fp);
  188. if ($info['timed_out']) {
  189. $result->code = -1;
  190. $result->error = 'request timed out';
  191. return $result;
  192. }
  193.  
  194. // Parse response headers from the response body.
  195. // Be tolerant of malformed HTTP responses that separate header and body with
  196. // \n\n or \r\r instead of \r\n\r\n.
  197. list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
  198. $response = preg_split("/\r\n|\n|\r/", $response);
  199.  
  200. // Parse the response status line.
  201. $response_array = explode(' ', trim(array_shift($response)), 3);
  202. // Set up empty values.
  203. $response_status_array = array(
  204. 'reason_phrase' => '',
  205. );
  206. $response_status_array['http_version'] = $response_array[0];
  207. $response_status_array['response_code'] = $response_array[1];
  208. if (isset($response_array[2])) {
  209. $response_status_array['reason_phrase'] = $response_array[2];
  210. }
  211.  
  212. $result->protocol = $response_status_array['http_version'];
  213. $result->status_message = $response_status_array['reason_phrase'];
  214. $code = $response_status_array['response_code'];
  215. $result->headers = array();
  216.  
  217. // Parse the response headers.
  218. while ($line = trim(array_shift($response))) {
  219. list($name, $value) = explode(':', $line, 2);
  220. $name = strtolower($name);
  221. if (isset($result->headers[$name]) && $name == 'set-cookie') {
  222.  
  223. // RFC 2109: the Set-Cookie response header comprises the token Set-
  224. // Cookie:, followed by a comma-separated list of one or more cookies.
  225. $result->headers[$name] .= ',' . trim($value);
  226. }
  227. else {
  228. $result->headers[$name] = trim($value);
  229. }
  230. }
  231. $responses = array(
  232. 100 => 'Continue',
  233. 101 => 'Switching Protocols',
  234. 200 => 'OK',
  235. 201 => 'Created',
  236. 202 => 'Accepted',
  237. 203 => 'Non-Authoritative Information',
  238. 204 => 'No Content',
  239. 205 => 'Reset Content',
  240. 206 => 'Partial Content',
  241. 300 => 'Multiple Choices',
  242. 301 => 'Moved Permanently',
  243. 302 => 'Found',
  244. 303 => 'See Other',
  245. 304 => 'Not Modified',
  246. 305 => 'Use Proxy',
  247. 307 => 'Temporary Redirect',
  248. 400 => 'Bad Request',
  249. 401 => 'Unauthorized',
  250. 402 => 'Payment Required',
  251. 403 => 'Forbidden',
  252. 404 => 'Not Found',
  253. 405 => 'Method Not Allowed',
  254. 406 => 'Not Acceptable',
  255. 407 => 'Proxy Authentication Required',
  256. 408 => 'Request Time-out',
  257. 409 => 'Conflict',
  258. 410 => 'Gone',
  259. 411 => 'Length Required',
  260. 412 => 'Precondition Failed',
  261. 413 => 'Request Entity Too Large',
  262. 414 => 'Request-URI Too Large',
  263. 415 => 'Unsupported Media Type',
  264. 416 => 'Requested range not satisfiable',
  265. 417 => 'Expectation Failed',
  266. 500 => 'Internal Server Error',
  267. 501 => 'Not Implemented',
  268. 502 => 'Bad Gateway',
  269. 503 => 'Service Unavailable',
  270. 504 => 'Gateway Time-out',
  271. 505 => 'HTTP Version not supported',
  272. );
  273.  
  274. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  275. // base code in their class.
  276. if (!isset($responses[$code])) {
  277. $code = floor($code / 100) * 100;
  278. }
  279. $result->code = $code;
  280. switch ($code) {
  281. // OK
  282. case 200:
  283. // Created
  284. case 201:
  285. // Accepted
  286. case 202:
  287. // Non-Authoritative Information
  288. case 203:
  289. // No Content
  290. case 204:
  291. // Reset Content
  292. case 205:
  293. // Partial Content
  294. case 206:
  295. // Not modified
  296. case 304:
  297. break;
  298. // Moved permanently
  299. case 301:
  300. // Moved temporarily
  301. case 302:
  302. // Moved temporarily
  303. case 307:
  304. $location = $result->headers['location'];
  305. $stop = microtime(TRUE);
  306. $diff = round(($stop - $timer['start']) * 1000, 2);
  307. if (isset($timer['time'])) {
  308. $diff += $timer['time'];
  309. }
  310. $options['timeout'] -= $diff / 1000;
  311. if ($options['timeout'] <= 0) {
  312. $result->code = -1;
  313. $result->error = 'request timed out';
  314. }
  315. elseif ($options['max_redirects']) {
  316.  
  317. // Redirect to the new location.
  318. $options['max_redirects']--;
  319. $result = request($location, $options);
  320. $result->redirect_code = $code;
  321. }
  322. if (!isset($result->redirect_url)) {
  323. $result->redirect_url = $location;
  324. }
  325. break;
  326. default:
  327. $result->error = $result->status_message;
  328. }
  329. return $result;
  330. }
Programming Language: PHP