5 * Inspired by Requests for Python.
7 * Based on concepts from SimplePie_File, RequestCore and WP_Http.
15 * Inspired by Requests for Python.
17 * Based on concepts from SimplePie_File, RequestCore and WP_Http.
55 const DELETE = 'DELETE';
60 * @link http://tools.ietf.org/html/rfc5789
63 const PATCH = 'PATCH';
66 * Default size of buffer size to read streams
70 const BUFFER_SIZE = 1160;
73 * Current version of Requests
77 const VERSION = '1.6';
80 * Registered transport classes
84 protected static $transports = array();
87 * Selected transport name
89 * Use {@see get_transport()} instead
93 public static $transport = array();
96 * This is a static class, do not instantiate it
100 private function __construct() {}
103 * Autoloader for Requests
105 * Register this with {@see register_autoloader()} if you'd like to avoid
106 * having to create your own.
108 * (You can also use `spl_autoload_register` directly if you'd prefer.)
110 * @codeCoverageIgnore
112 * @param string $class Class name to load
114 public static function autoloader($class) {
115 // Check that the class starts with "Requests"
116 if (strpos($class, 'Requests') !== 0) {
120 $file = str_replace('_', '/', $class);
121 if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
122 require_once(dirname(__FILE__) . '/' . $file . '.php');
127 * Register the built-in autoloader
129 * @codeCoverageIgnore
131 public static function register_autoloader() {
132 spl_autoload_register(array('Requests', 'autoloader'));
136 * Register a transport
138 * @param string $transport Transport class to add, must support the Requests_Transport interface
140 public static function add_transport($transport) {
141 if (empty(self::$transports)) {
142 self::$transports = array(
143 'Requests_Transport_cURL',
144 'Requests_Transport_fsockopen',
148 self::$transports = array_merge(self::$transports, array($transport));
152 * Get a working transport
154 * @throws Requests_Exception If no valid transport is found (`notransport`)
155 * @return Requests_Transport
157 protected static function get_transport($capabilities = array()) {
158 // Caching code, don't bother testing coverage
159 // @codeCoverageIgnoreStart
160 // array of capabilities as a string to be used as an array key
161 ksort($capabilities);
162 $cap_string = serialize($capabilities);
164 // Don't search for a transport if it's already been done for these $capabilities
165 if (isset(self::$transport[$cap_string]) && self::$transport[$cap_string] !== null) {
166 return new self::$transport[$cap_string]();
168 // @codeCoverageIgnoreEnd
170 if (empty(self::$transports)) {
171 self::$transports = array(
172 'Requests_Transport_cURL',
173 'Requests_Transport_fsockopen',
177 // Find us a working transport
178 foreach (self::$transports as $class) {
179 if (!class_exists($class))
182 $result = call_user_func(array($class, 'test'), $capabilities);
184 self::$transport[$cap_string] = $class;
188 if (self::$transport[$cap_string] === null) {
189 throw new Requests_Exception('No working transports found', 'notransport', self::$transports);
192 return new self::$transport[$cap_string]();
198 * @param array $headers
199 * @param array $options
200 * @return Requests_Response
205 public static function get($url, $headers = array(), $options = array()) {
206 return self::request($url, $headers, null, self::GET, $options);
210 * Send a HEAD request
212 public static function head($url, $headers = array(), $options = array()) {
213 return self::request($url, $headers, null, self::HEAD, $options);
217 * Send a DELETE request
219 public static function delete($url, $headers = array(), $options = array()) {
220 return self::request($url, $headers, null, self::DELETE, $options);
227 * @param array $headers
229 * @param array $options
230 * @return Requests_Response
233 * Send a POST request
235 public static function post($url, $headers = array(), $data = array(), $options = array()) {
236 return self::request($url, $headers, $data, self::POST, $options);
241 public static function put($url, $headers = array(), $data = array(), $options = array()) {
242 return self::request($url, $headers, $data, self::PUT, $options);
246 * Send a PATCH request
248 * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the
249 * specification recommends that should send an ETag
251 * @link http://tools.ietf.org/html/rfc5789
253 public static function patch($url, $headers, $data = array(), $options = array()) {
254 return self::request($url, $headers, $data, self::PATCH, $options);
259 * Main interface for HTTP requests
261 * This method initiates a request and sends it via a transport before
264 * The `$options` parameter takes an associative array with the following
267 * - `timeout`: How long should we wait for a response?
268 * (float, seconds with a millisecond precision, default: 10, example: 0.01)
269 * - `connect_timeout`: How long should we wait while trying to connect?
270 * (float, seconds with a millisecond precision, default: 10, example: 0.01)
271 * - `useragent`: Useragent to send to the server
272 * (string, default: php-requests/$version)
273 * - `follow_redirects`: Should we follow 3xx redirects?
274 * (boolean, default: true)
275 * - `redirects`: How many times should we redirect before erroring?
276 * (integer, default: 10)
277 * - `blocking`: Should we block processing on this request?
278 * (boolean, default: true)
279 * - `filename`: File to stream the body to instead.
280 * (string|boolean, default: false)
281 * - `auth`: Authentication handler or array of user/password details to use
282 * for Basic authentication
283 * (Requests_Auth|array|boolean, default: false)
284 * - `proxy`: Proxy details to use for proxy by-passing and authentication
285 * (Requests_Proxy|array|boolean, default: false)
286 * - `max_bytes`: Limit for the response body size.
287 * (integer|boolean, default: false)
288 * - `idn`: Enable IDN parsing
289 * (boolean, default: true)
290 * - `transport`: Custom transport. Either a class name, or a
291 * transport object. Defaults to the first working transport from
292 * {@see getTransport()}
293 * (string|Requests_Transport, default: {@see getTransport()})
294 * - `hooks`: Hooks handler.
295 * (Requests_Hooker, default: new Requests_Hooks())
296 * - `verify`: Should we verify SSL certificates? Allows passing in a custom
297 * certificate file as a string. (Using true uses the system-wide root
298 * certificate store instead, but this may have different behaviour
299 * across transports.)
300 * (string|boolean, default: library/Requests/Transport/cacert.pem)
301 * - `verifyname`: Should we verify the common name in the SSL certificate?
302 * (boolean: default, true)
304 * @throws Requests_Exception On invalid URLs (`nonhttp`)
306 * @param string $url URL to request
307 * @param array $headers Extra headers to send with the request
308 * @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
309 * @param string $type HTTP request type (use Requests constants)
310 * @param array $options Options for the request (see description for more information)
311 * @return Requests_Response
313 public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) {
314 if (empty($options['type'])) {
315 $options['type'] = $type;
317 $options = array_merge(self::get_default_options(), $options);
319 self::set_defaults($url, $headers, $data, $type, $options);
321 $options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options));
323 if (!empty($options['transport'])) {
324 $transport = $options['transport'];
326 if (is_string($options['transport'])) {
327 $transport = new $transport();
330 $need_ssl = (0 === stripos($url, 'https://'));
331 $capabilities = array('ssl' => $need_ssl);
332 $transport = self::get_transport($capabilities);
334 $response = $transport->request($url, $headers, $data, $options);
336 $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
338 return self::parse_response($response, $url, $headers, $data, $options);
342 * Send multiple HTTP requests simultaneously
344 * The `$requests` parameter takes an associative or indexed array of
345 * request fields. The key of each request can be used to match up the
346 * request with the returned data, or with the request passed into your
347 * `multiple.request.complete` callback.
349 * The request fields value is an associative array with the following keys:
351 * - `url`: Request URL Same as the `$url` parameter to
352 * {@see Requests::request}
354 * - `headers`: Associative array of header fields. Same as the `$headers`
355 * parameter to {@see Requests::request}
356 * (array, default: `array()`)
357 * - `data`: Associative array of data fields or a string. Same as the
358 * `$data` parameter to {@see Requests::request}
359 * (array|string, default: `array()`)
360 * - `type`: HTTP request type (use Requests constants). Same as the `$type`
361 * parameter to {@see Requests::request}
362 * (string, default: `Requests::GET`)
363 * - `cookies`: Associative array of cookie name to value, or cookie jar.
364 * (array|Requests_Cookie_Jar)
366 * If the `$options` parameter is specified, individual requests will
367 * inherit options from it. This can be used to use a single hooking system,
368 * or set all the types to `Requests::POST`, for example.
370 * In addition, the `$options` parameter takes the following global options:
372 * - `complete`: A callback for when a request is complete. Takes two
373 * parameters, a Requests_Response/Requests_Exception reference, and the
374 * ID from the request array (Note: this can also be overridden on a
375 * per-request basis, although that's a little silly)
378 * @param array $requests Requests data (see description for more information)
379 * @param array $options Global and default options (see {@see Requests::request})
380 * @return array Responses (either Requests_Response or a Requests_Exception object)
382 public static function request_multiple($requests, $options = array()) {
383 $options = array_merge(self::get_default_options(true), $options);
385 if (!empty($options['hooks'])) {
386 $options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
387 if (!empty($options['complete'])) {
388 $options['hooks']->register('multiple.request.complete', $options['complete']);
392 foreach ($requests as $id => &$request) {
393 if (!isset($request['headers'])) {
394 $request['headers'] = array();
396 if (!isset($request['data'])) {
397 $request['data'] = array();
399 if (!isset($request['type'])) {
400 $request['type'] = self::GET;
402 if (!isset($request['options'])) {
403 $request['options'] = $options;
404 $request['options']['type'] = $request['type'];
407 if (empty($request['options']['type'])) {
408 $request['options']['type'] = $request['type'];
410 $request['options'] = array_merge($options, $request['options']);
413 self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
415 // Ensure we only hook in once
416 if ($request['options']['hooks'] !== $options['hooks']) {
417 $request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
418 if (!empty($request['options']['complete'])) {
419 $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
425 if (!empty($options['transport'])) {
426 $transport = $options['transport'];
428 if (is_string($options['transport'])) {
429 $transport = new $transport();
433 $transport = self::get_transport();
435 $responses = $transport->request_multiple($requests, $options);
437 foreach ($responses as $id => &$response) {
438 // If our hook got messed with somehow, ensure we end up with the
440 if (is_string($response)) {
441 $request = $requests[$id];
442 self::parse_multiple($response, $request);
443 $request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id));
451 * Get the default options
453 * @see Requests::request() for values returned by this method
454 * @param boolean $multirequest Is this a multirequest?
455 * @return array Default option values
457 protected static function get_default_options($multirequest = false) {
460 'connect_timeout' => 10,
461 'useragent' => 'php-requests/' . self::VERSION,
464 'follow_redirects' => true,
471 'max_bytes' => false,
475 'verify' => dirname( __FILE__ ) . '/Requests/Transport/cacert.pem',
476 'verifyname' => true,
478 if ($multirequest !== false) {
479 $defaults['complete'] = null;
485 * Set the default values
487 * @param string $url URL to request
488 * @param array $headers Extra headers to send with the request
489 * @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
490 * @param string $type HTTP request type
491 * @param array $options Options for the request
492 * @return array $options
494 protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
495 if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
496 throw new Requests_Exception('Only HTTP(S) requests are handled.', 'nonhttp', $url);
499 if (empty($options['hooks'])) {
500 $options['hooks'] = new Requests_Hooks();
503 if (is_array($options['auth'])) {
504 $options['auth'] = new Requests_Auth_Basic($options['auth']);
506 if ($options['auth'] !== false) {
507 $options['auth']->register($options['hooks']);
510 if (!empty($options['proxy'])) {
511 $options['proxy'] = new Requests_Proxy_HTTP($options['proxy']);
513 if ($options['proxy'] !== false) {
514 $options['proxy']->register($options['hooks']);
517 if (is_array($options['cookies'])) {
518 $options['cookies'] = new Requests_Cookie_Jar($options['cookies']);
520 elseif (empty($options['cookies'])) {
521 $options['cookies'] = new Requests_Cookie_Jar();
523 if ($options['cookies'] !== false) {
524 $options['cookies']->register($options['hooks']);
527 if ($options['idn'] !== false) {
528 $iri = new Requests_IRI($url);
529 $iri->host = Requests_IDNAEncoder::encode($iri->ihost);
535 * HTTP response parser
537 * @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`)
538 * @throws Requests_Exception On missing head/body separator (`noversion`)
539 * @throws Requests_Exception On missing head/body separator (`toomanyredirects`)
541 * @param string $headers Full response text including headers and body
542 * @param string $url Original request URL
543 * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
544 * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
545 * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
546 * @return Requests_Response
548 protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
549 $return = new Requests_Response();
550 if (!$options['blocking']) {
554 $return->raw = $headers;
557 if (!$options['filename']) {
558 if (($pos = strpos($headers, "\r\n\r\n")) === false) {
560 throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator');
563 $headers = substr($return->raw, 0, $pos);
564 $return->body = substr($return->raw, $pos + strlen("\n\r\n\r"));
569 // Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
570 $headers = str_replace("\r\n", "\n", $headers);
571 // Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
572 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
573 $headers = explode("\n", $headers);
574 preg_match('#^HTTP/1\.\d[ \t]+(\d+)#i', array_shift($headers), $matches);
575 if (empty($matches)) {
576 throw new Requests_Exception('Response could not be parsed', 'noversion', $headers);
578 $return->status_code = (int) $matches[1];
579 if ($return->status_code >= 200 && $return->status_code < 300) {
580 $return->success = true;
583 foreach ($headers as $header) {
584 list($key, $value) = explode(':', $header, 2);
585 $value = trim($value);
586 preg_replace('#(\s+)#i', ' ', $value);
587 $return->headers[$key] = $value;
589 if (isset($return->headers['transfer-encoding'])) {
590 $return->body = self::decode_chunked($return->body);
591 unset($return->headers['transfer-encoding']);
593 if (isset($return->headers['content-encoding'])) {
594 $return->body = self::decompress($return->body);
597 //fsockopen and cURL compatibility
598 if (isset($return->headers['connection'])) {
599 unset($return->headers['connection']);
602 $options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options));
604 if ((in_array($return->status_code, array(300, 301, 302, 303, 307)) || $return->status_code > 307 && $return->status_code < 400) && $options['follow_redirects'] === true) {
605 if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
606 if ($return->status_code === 303) {
607 $options['type'] = Requests::GET;
609 $options['redirected']++;
610 $location = $return->headers['location'];
611 if (strpos ($location, 'http://') !== 0 && strpos ($location, 'https://') !== 0) {
612 // relative redirect, for compatibility make it absolute
613 $location = Requests_IRI::absolutize($url, $location);
614 $location = $location->uri;
616 $redirected = self::request($location, $req_headers, $req_data, false, $options);
617 $redirected->history[] = $return;
620 elseif ($options['redirected'] >= $options['redirects']) {
621 throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return);
625 $return->redirects = $options['redirected'];
627 $options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options));
632 * Callback for `transport.internal.parse_response`
634 * Internal use only. Converts a raw HTTP response to a Requests_Response
635 * while still executing a multiple request.
637 * @param string $headers Full response text including headers and body
638 * @param array $request Request data as passed into {@see Requests::request_multiple()}
639 * @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object
641 public static function parse_multiple(&$response, $request) {
643 $response = self::parse_response($response, $request['url'], $request['headers'], $request['data'], $request['options']);
645 catch (Requests_Exception $e) {
651 * Decoded a chunked body as per RFC 2616
653 * @see http://tools.ietf.org/html/rfc2616#section-3.6.1
654 * @param string $data Chunked body
655 * @return string Decoded body
657 protected static function decode_chunked($data) {
658 if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($data))) {
666 $is_chunked = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches );
668 // Looks like it's not chunked after all
672 $length = hexdec(trim($matches[1]));
674 // Ignore trailer headers
678 $chunk_length = strlen($matches[0]);
679 $decoded .= $part = substr($encoded, $chunk_length, $length);
680 $encoded = substr($encoded, $chunk_length + $length + 2);
682 if (trim($encoded) === '0' || empty($encoded)) {
687 // We'll never actually get down here
688 // @codeCoverageIgnoreStart
690 // @codeCoverageIgnoreEnd
693 * Convert a key => value array to a 'key: value' array for headers
695 * @param array $array Dictionary of header values
696 * @return array List of headers
698 public static function flatten($array) {
700 foreach ($array as $key => $value) {
701 $return[] = "$key: $value";
707 * Convert a key => value array to a 'key: value' array for headers
709 * @deprecated Misspelling of {@see Requests::flatten}
710 * @param array $array Dictionary of header values
711 * @return array List of headers
713 public static function flattern($array) {
714 return self::flatten($array);
718 * Decompress an encoded body
720 * Implements gzip, compress and deflate. Guesses which it is by attempting
723 * @todo Make this smarter by defaulting to whatever the headers say first
724 * @param string $data Compressed data in one of the above formats
725 * @return string Decompressed string
727 public static function decompress($data) {
728 if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") {
729 // Not actually compressed. Probably cURL ruining this for us.
733 if (function_exists('gzdecode') && ($decoded = @gzdecode($data)) !== false) {
736 elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) {
739 elseif (($decoded = self::compatible_gzinflate($data)) !== false) {
742 elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) {
750 * Decompression of deflated string while staying compatible with the majority of servers.
752 * Certain Servers will return deflated data with headers which PHP's gzinflate()
753 * function cannot handle out of the box. The following function has been created from
754 * various snippets on the gzinflate() PHP documentation.
756 * Warning: Magic numbers within. Due to the potential different formats that the compressed
757 * data may be returned in, some "magic offsets" are needed to ensure proper decompression
758 * takes place. For a simple progmatic way to determine the magic offset in use, see:
759 * http://core.trac.wordpress.org/ticket/18273
762 * @link http://core.trac.wordpress.org/ticket/18273
763 * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
764 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
766 * @param string $gzData String to decompress.
767 * @return string|bool False on failure.
769 public static function compatible_gzinflate($gzData) {
770 // Compressed data might contain a full zlib header, if so strip it for
772 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
774 $flg = ord( substr($gzData, 3, 1) );
777 list($xlen) = unpack('v', substr($gzData, $i, 2) );
781 $i = strpos($gzData, "\0", $i) + 1;
783 $i = strpos($gzData, "\0", $i) + 1;
787 $decompressed = self::compatible_gzinflate( substr( $gzData, $i ) );
788 if ( false !== $decompressed ) {
789 return $decompressed;
793 // If the data is Huffman Encoded, we must first strip the leading 2
794 // byte Huffman marker for gzinflate()
795 // The response is Huffman coded by many compressors such as
796 // java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's
797 // System.IO.Compression.DeflateStream.
799 // See http://decompres.blogspot.com/ for a quick explanation of this
801 $huffman_encoded = false;
803 // low nibble of first byte should be 0x08
804 list( , $first_nibble ) = unpack( 'h', $gzData );
806 // First 2 bytes should be divisible by 0x1F
807 list( , $first_two_bytes ) = unpack( 'n', $gzData );
809 if ( 0x08 == $first_nibble && 0 == ( $first_two_bytes % 0x1F ) )
810 $huffman_encoded = true;
812 if ( $huffman_encoded ) {
813 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 2 ) ) ) )
814 return $decompressed;
817 if ( "\x50\x4b\x03\x04" == substr( $gzData, 0, 4 ) ) {
818 // ZIP file format header
819 // Offset 6: 2 bytes, General-purpose field
820 // Offset 26: 2 bytes, filename length
821 // Offset 28: 2 bytes, optional field length
822 // Offset 30: Filename field, followed by optional field, followed
823 // immediately by data
824 list( , $general_purpose_flag ) = unpack( 'v', substr( $gzData, 6, 2 ) );
826 // If the file has been compressed on the fly, 0x08 bit is set of
827 // the general purpose field. We can use this to differentiate
828 // between a compressed document, and a ZIP file
829 $zip_compressed_on_the_fly = ( 0x08 == (0x08 & $general_purpose_flag ) );
831 if ( ! $zip_compressed_on_the_fly ) {
832 // Don't attempt to decode a compressed zip file
836 // Determine the first byte of data, based on the above ZIP header
838 $first_file_start = array_sum( unpack( 'v2', substr( $gzData, 26, 4 ) ) );
839 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 30 + $first_file_start ) ) ) ) {
840 return $decompressed;
845 // Finally fall back to straight gzinflate
846 if ( false !== ( $decompressed = @gzinflate( $gzData ) ) ) {
847 return $decompressed;
850 // Fallback for all above failing, not expected, but included for
851 // debugging and preventing regressions and to track stats
852 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 2 ) ) ) ) {
853 return $decompressed;
859 public static function match_domain($host, $reference) {
860 // Check for a direct match
861 if ($host === $reference) {
865 // Calculate the valid wildcard match if the host is not an IP address
866 // Also validates that the host has 3 parts or more, as per Firefox's
868 $parts = explode('.', $host);
869 if (ip2long($host) === false && count($parts) >= 3) {
871 $wildcard = implode('.', $parts);
872 if ($wildcard === $reference) {