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 * Current version of Requests
70 const VERSION = '1.6';
73 * Registered transport classes
77 protected static $transports = array();
80 * Selected transport name
82 * Use {@see get_transport()} instead
86 public static $transport = array();
89 * This is a static class, do not instantiate it
93 private function __construct() {}
96 * Autoloader for Requests
98 * Register this with {@see register_autoloader()} if you'd like to avoid
99 * having to create your own.
101 * (You can also use `spl_autoload_register` directly if you'd prefer.)
103 * @codeCoverageIgnore
105 * @param string $class Class name to load
107 public static function autoloader($class) {
108 // Check that the class starts with "Requests"
109 if (strpos($class, 'Requests') !== 0) {
113 $file = str_replace('_', '/', $class);
114 if (file_exists(dirname(__FILE__) . '/' . $file . '.php')) {
115 require_once(dirname(__FILE__) . '/' . $file . '.php');
120 * Register the built-in autoloader
122 * @codeCoverageIgnore
124 public static function register_autoloader() {
125 spl_autoload_register(array('Requests', 'autoloader'));
129 * Register a transport
131 * @param string $transport Transport class to add, must support the Requests_Transport interface
133 public static function add_transport($transport) {
134 if (empty(self::$transports)) {
135 self::$transports = array(
136 'Requests_Transport_cURL',
137 'Requests_Transport_fsockopen',
141 self::$transports = array_merge(self::$transports, array($transport));
145 * Get a working transport
147 * @throws Requests_Exception If no valid transport is found (`notransport`)
148 * @return Requests_Transport
150 protected static function get_transport($capabilities = array()) {
151 // Caching code, don't bother testing coverage
152 // @codeCoverageIgnoreStart
153 // array of capabilities as a string to be used as an array key
154 ksort($capabilities);
155 $cap_string = serialize($capabilities);
157 // Don't search for a transport if it's already been done for these $capabilities
158 if (isset(self::$transport[$cap_string]) && self::$transport[$cap_string] !== null) {
159 return new self::$transport[$cap_string]();
161 // @codeCoverageIgnoreEnd
163 if (empty(self::$transports)) {
164 self::$transports = array(
165 'Requests_Transport_cURL',
166 'Requests_Transport_fsockopen',
170 // Find us a working transport
171 foreach (self::$transports as $class) {
172 if (!class_exists($class))
175 $result = call_user_func(array($class, 'test'), $capabilities);
177 self::$transport[$cap_string] = $class;
181 if (self::$transport[$cap_string] === null) {
182 throw new Requests_Exception('No working transports found', 'notransport', self::$transports);
185 return new self::$transport[$cap_string]();
191 * @param array $headers
192 * @param array $options
193 * @return Requests_Response
198 public static function get($url, $headers = array(), $options = array()) {
199 return self::request($url, $headers, null, self::GET, $options);
203 * Send a HEAD request
205 public static function head($url, $headers = array(), $options = array()) {
206 return self::request($url, $headers, null, self::HEAD, $options);
210 * Send a DELETE request
212 public static function delete($url, $headers = array(), $options = array()) {
213 return self::request($url, $headers, null, self::DELETE, $options);
220 * @param array $headers
222 * @param array $options
223 * @return Requests_Response
226 * Send a POST request
228 public static function post($url, $headers = array(), $data = array(), $options = array()) {
229 return self::request($url, $headers, $data, self::POST, $options);
234 public static function put($url, $headers = array(), $data = array(), $options = array()) {
235 return self::request($url, $headers, $data, self::PUT, $options);
239 * Send a PATCH request
241 * Note: Unlike {@see post} and {@see put}, `$headers` is required, as the
242 * specification recommends that should send an ETag
244 * @link http://tools.ietf.org/html/rfc5789
246 public static function patch($url, $headers, $data = array(), $options = array()) {
247 return self::request($url, $headers, $data, self::PATCH, $options);
252 * Main interface for HTTP requests
254 * This method initiates a request and sends it via a transport before
257 * The `$options` parameter takes an associative array with the following
260 * - `timeout`: How long should we wait for a response?
261 * (float, seconds with a millisecond precision, default: 10, example: 0.01)
262 * - `connect_timeout`: How long should we wait while trying to connect?
263 * (float, seconds with a millisecond precision, default: 10, example: 0.01)
264 * - `useragent`: Useragent to send to the server
265 * (string, default: php-requests/$version)
266 * - `follow_redirects`: Should we follow 3xx redirects?
267 * (boolean, default: true)
268 * - `redirects`: How many times should we redirect before erroring?
269 * (integer, default: 10)
270 * - `blocking`: Should we block processing on this request?
271 * (boolean, default: true)
272 * - `filename`: File to stream the body to instead.
273 * (string|boolean, default: false)
274 * - `auth`: Authentication handler or array of user/password details to use
275 * for Basic authentication
276 * (Requests_Auth|array|boolean, default: false)
277 * - `proxy`: Proxy details to use for proxy by-passing and authentication
278 * (Requests_Proxy|array|boolean, default: false)
279 * - `idn`: Enable IDN parsing
280 * (boolean, default: true)
281 * - `transport`: Custom transport. Either a class name, or a
282 * transport object. Defaults to the first working transport from
283 * {@see getTransport()}
284 * (string|Requests_Transport, default: {@see getTransport()})
285 * - `hooks`: Hooks handler.
286 * (Requests_Hooker, default: new Requests_Hooks())
287 * - `verify`: Should we verify SSL certificates? Allows passing in a custom
288 * certificate file as a string. (Using true uses the system-wide root
289 * certificate store instead, but this may have different behaviour
290 * across transports.)
291 * (string|boolean, default: library/Requests/Transport/cacert.pem)
292 * - `verifyname`: Should we verify the common name in the SSL certificate?
293 * (boolean: default, true)
295 * @throws Requests_Exception On invalid URLs (`nonhttp`)
297 * @param string $url URL to request
298 * @param array $headers Extra headers to send with the request
299 * @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
300 * @param string $type HTTP request type (use Requests constants)
301 * @param array $options Options for the request (see description for more information)
302 * @return Requests_Response
304 public static function request($url, $headers = array(), $data = array(), $type = self::GET, $options = array()) {
305 if (empty($options['type'])) {
306 $options['type'] = $type;
308 $options = array_merge(self::get_default_options(), $options);
310 self::set_defaults($url, $headers, $data, $type, $options);
312 $options['hooks']->dispatch('requests.before_request', array(&$url, &$headers, &$data, &$type, &$options));
314 if (!empty($options['transport'])) {
315 $transport = $options['transport'];
317 if (is_string($options['transport'])) {
318 $transport = new $transport();
321 $need_ssl = (0 === stripos($url, 'https://'));
322 $capabilities = array('ssl' => $need_ssl);
323 $transport = self::get_transport($capabilities);
325 $response = $transport->request($url, $headers, $data, $options);
327 $options['hooks']->dispatch('requests.before_parse', array(&$response, $url, $headers, $data, $type, $options));
329 return self::parse_response($response, $url, $headers, $data, $options);
333 * Send multiple HTTP requests simultaneously
335 * The `$requests` parameter takes an associative or indexed array of
336 * request fields. The key of each request can be used to match up the
337 * request with the returned data, or with the request passed into your
338 * `multiple.request.complete` callback.
340 * The request fields value is an associative array with the following keys:
342 * - `url`: Request URL Same as the `$url` parameter to
343 * {@see Requests::request}
345 * - `headers`: Associative array of header fields. Same as the `$headers`
346 * parameter to {@see Requests::request}
347 * (array, default: `array()`)
348 * - `data`: Associative array of data fields or a string. Same as the
349 * `$data` parameter to {@see Requests::request}
350 * (array|string, default: `array()`)
351 * - `type`: HTTP request type (use Requests constants). Same as the `$type`
352 * parameter to {@see Requests::request}
353 * (string, default: `Requests::GET`)
354 * - `cookies`: Associative array of cookie name to value, or cookie jar.
355 * (array|Requests_Cookie_Jar)
357 * If the `$options` parameter is specified, individual requests will
358 * inherit options from it. This can be used to use a single hooking system,
359 * or set all the types to `Requests::POST`, for example.
361 * In addition, the `$options` parameter takes the following global options:
363 * - `complete`: A callback for when a request is complete. Takes two
364 * parameters, a Requests_Response/Requests_Exception reference, and the
365 * ID from the request array (Note: this can also be overridden on a
366 * per-request basis, although that's a little silly)
369 * @param array $requests Requests data (see description for more information)
370 * @param array $options Global and default options (see {@see Requests::request})
371 * @return array Responses (either Requests_Response or a Requests_Exception object)
373 public static function request_multiple($requests, $options = array()) {
374 $options = array_merge(self::get_default_options(true), $options);
376 if (!empty($options['hooks'])) {
377 $options['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
378 if (!empty($options['complete'])) {
379 $options['hooks']->register('multiple.request.complete', $options['complete']);
383 foreach ($requests as $id => &$request) {
384 if (!isset($request['headers'])) {
385 $request['headers'] = array();
387 if (!isset($request['data'])) {
388 $request['data'] = array();
390 if (!isset($request['type'])) {
391 $request['type'] = self::GET;
393 if (!isset($request['options'])) {
394 $request['options'] = $options;
395 $request['options']['type'] = $request['type'];
398 if (empty($request['options']['type'])) {
399 $request['options']['type'] = $request['type'];
401 $request['options'] = array_merge($options, $request['options']);
404 self::set_defaults($request['url'], $request['headers'], $request['data'], $request['type'], $request['options']);
406 // Ensure we only hook in once
407 if ($request['options']['hooks'] !== $options['hooks']) {
408 $request['options']['hooks']->register('transport.internal.parse_response', array('Requests', 'parse_multiple'));
409 if (!empty($request['options']['complete'])) {
410 $request['options']['hooks']->register('multiple.request.complete', $request['options']['complete']);
416 if (!empty($options['transport'])) {
417 $transport = $options['transport'];
419 if (is_string($options['transport'])) {
420 $transport = new $transport();
424 $transport = self::get_transport();
426 $responses = $transport->request_multiple($requests, $options);
428 foreach ($responses as $id => &$response) {
429 // If our hook got messed with somehow, ensure we end up with the
431 if (is_string($response)) {
432 $request = $requests[$id];
433 self::parse_multiple($response, $request);
434 $request['options']['hooks']->dispatch('multiple.request.complete', array(&$response, $id));
442 * Get the default options
444 * @see Requests::request() for values returned by this method
445 * @param boolean $multirequest Is this a multirequest?
446 * @return array Default option values
448 protected static function get_default_options($multirequest = false) {
451 'connect_timeout' => 10,
452 'useragent' => 'php-requests/' . self::VERSION,
455 'follow_redirects' => true,
465 'verify' => dirname( __FILE__ ) . '/Requests/Transport/cacert.pem',
466 'verifyname' => true,
468 if ($multirequest !== false) {
469 $defaults['complete'] = null;
475 * Set the default values
477 * @param string $url URL to request
478 * @param array $headers Extra headers to send with the request
479 * @param array $data Data to send either as a query string for GET/HEAD requests, or in the body for POST requests
480 * @param string $type HTTP request type
481 * @param array $options Options for the request
482 * @return array $options
484 protected static function set_defaults(&$url, &$headers, &$data, &$type, &$options) {
485 if (!preg_match('/^http(s)?:\/\//i', $url, $matches)) {
486 throw new Requests_Exception('Only HTTP requests are handled.', 'nonhttp', $url);
489 if (empty($options['hooks'])) {
490 $options['hooks'] = new Requests_Hooks();
493 if (is_array($options['auth'])) {
494 $options['auth'] = new Requests_Auth_Basic($options['auth']);
496 if ($options['auth'] !== false) {
497 $options['auth']->register($options['hooks']);
500 if (!empty($options['proxy'])) {
501 $options['proxy'] = new Requests_Proxy_HTTP($options['proxy']);
503 if ($options['proxy'] !== false) {
504 $options['proxy']->register($options['hooks']);
507 if (is_array($options['cookies'])) {
508 $options['cookies'] = new Requests_Cookie_Jar($options['cookies']);
510 elseif (empty($options['cookies'])) {
511 $options['cookies'] = new Requests_Cookie_Jar();
513 if ($options['cookies'] !== false) {
514 $options['cookies']->register($options['hooks']);
517 if ($options['idn'] !== false) {
518 $iri = new Requests_IRI($url);
519 $iri->host = Requests_IDNAEncoder::encode($iri->ihost);
525 * HTTP response parser
527 * @throws Requests_Exception On missing head/body separator (`requests.no_crlf_separator`)
528 * @throws Requests_Exception On missing head/body separator (`noversion`)
529 * @throws Requests_Exception On missing head/body separator (`toomanyredirects`)
531 * @param string $headers Full response text including headers and body
532 * @param string $url Original request URL
533 * @param array $req_headers Original $headers array passed to {@link request()}, in case we need to follow redirects
534 * @param array $req_data Original $data array passed to {@link request()}, in case we need to follow redirects
535 * @param array $options Original $options array passed to {@link request()}, in case we need to follow redirects
536 * @return Requests_Response
538 protected static function parse_response($headers, $url, $req_headers, $req_data, $options) {
539 $return = new Requests_Response();
540 if (!$options['blocking']) {
544 $return->raw = $headers;
547 if (!$options['filename']) {
548 if (($pos = strpos($headers, "\r\n\r\n")) === false) {
550 throw new Requests_Exception('Missing header/body separator', 'requests.no_crlf_separator');
553 $headers = substr($return->raw, 0, $pos);
554 $return->body = substr($return->raw, $pos + strlen("\n\r\n\r"));
559 // Pretend CRLF = LF for compatibility (RFC 2616, section 19.3)
560 $headers = str_replace("\r\n", "\n", $headers);
561 // Unfold headers (replace [CRLF] 1*( SP | HT ) with SP) as per RFC 2616 (section 2.2)
562 $headers = preg_replace('/\n[ \t]/', ' ', $headers);
563 $headers = explode("\n", $headers);
564 preg_match('#^HTTP/1\.\d[ \t]+(\d+)#i', array_shift($headers), $matches);
565 if (empty($matches)) {
566 throw new Requests_Exception('Response could not be parsed', 'noversion', $headers);
568 $return->status_code = (int) $matches[1];
569 if ($return->status_code >= 200 && $return->status_code < 300) {
570 $return->success = true;
573 foreach ($headers as $header) {
574 list($key, $value) = explode(':', $header, 2);
575 $value = trim($value);
576 preg_replace('#(\s+)#i', ' ', $value);
577 $return->headers[$key] = $value;
579 if (isset($return->headers['transfer-encoding'])) {
580 $return->body = self::decode_chunked($return->body);
581 unset($return->headers['transfer-encoding']);
583 if (isset($return->headers['content-encoding'])) {
584 $return->body = self::decompress($return->body);
587 //fsockopen and cURL compatibility
588 if (isset($return->headers['connection'])) {
589 unset($return->headers['connection']);
592 $options['hooks']->dispatch('requests.before_redirect_check', array(&$return, $req_headers, $req_data, $options));
594 if ((in_array($return->status_code, array(300, 301, 302, 303, 307)) || $return->status_code > 307 && $return->status_code < 400) && $options['follow_redirects'] === true) {
595 if (isset($return->headers['location']) && $options['redirected'] < $options['redirects']) {
596 if ($return->status_code === 303) {
597 $options['type'] = Requests::GET;
599 $options['redirected']++;
600 $location = $return->headers['location'];
601 if (strpos ($location, 'http://') !== 0 && strpos ($location, 'https://') !== 0) {
602 // relative redirect, for compatibility make it absolute
603 $location = Requests_IRI::absolutize($url, $location);
604 $location = $location->uri;
606 $redirected = self::request($location, $req_headers, $req_data, false, $options);
607 $redirected->history[] = $return;
610 elseif ($options['redirected'] >= $options['redirects']) {
611 throw new Requests_Exception('Too many redirects', 'toomanyredirects', $return);
615 $return->redirects = $options['redirected'];
617 $options['hooks']->dispatch('requests.after_request', array(&$return, $req_headers, $req_data, $options));
622 * Callback for `transport.internal.parse_response`
624 * Internal use only. Converts a raw HTTP response to a Requests_Response
625 * while still executing a multiple request.
627 * @param string $headers Full response text including headers and body
628 * @param array $request Request data as passed into {@see Requests::request_multiple()}
629 * @return null `$response` is either set to a Requests_Response instance, or a Requests_Exception object
631 public static function parse_multiple(&$response, $request) {
633 $response = self::parse_response($response, $request['url'], $request['headers'], $request['data'], $request['options']);
635 catch (Requests_Exception $e) {
641 * Decoded a chunked body as per RFC 2616
643 * @see http://tools.ietf.org/html/rfc2616#section-3.6.1
644 * @param string $data Chunked body
645 * @return string Decoded body
647 protected static function decode_chunked($data) {
648 if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($data))) {
656 $is_chunked = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches );
658 // Looks like it's not chunked after all
662 $length = hexdec(trim($matches[1]));
664 // Ignore trailer headers
668 $chunk_length = strlen($matches[0]);
669 $decoded .= $part = substr($encoded, $chunk_length, $length);
670 $encoded = substr($encoded, $chunk_length + $length + 2);
672 if (trim($encoded) === '0' || empty($encoded)) {
677 // We'll never actually get down here
678 // @codeCoverageIgnoreStart
680 // @codeCoverageIgnoreEnd
683 * Convert a key => value array to a 'key: value' array for headers
685 * @param array $array Dictionary of header values
686 * @return array List of headers
688 public static function flatten($array) {
690 foreach ($array as $key => $value) {
691 $return[] = "$key: $value";
697 * Convert a key => value array to a 'key: value' array for headers
699 * @deprecated Misspelling of {@see Requests::flatten}
700 * @param array $array Dictionary of header values
701 * @return array List of headers
703 public static function flattern($array) {
704 return self::flatten($array);
708 * Decompress an encoded body
710 * Implements gzip, compress and deflate. Guesses which it is by attempting
713 * @todo Make this smarter by defaulting to whatever the headers say first
714 * @param string $data Compressed data in one of the above formats
715 * @return string Decompressed string
717 public static function decompress($data) {
718 if (substr($data, 0, 2) !== "\x1f\x8b" && substr($data, 0, 2) !== "\x78\x9c") {
719 // Not actually compressed. Probably cURL ruining this for us.
723 if (function_exists('gzdecode') && ($decoded = @gzdecode($data)) !== false) {
726 elseif (function_exists('gzinflate') && ($decoded = @gzinflate($data)) !== false) {
729 elseif (($decoded = self::compatible_gzinflate($data)) !== false) {
732 elseif (function_exists('gzuncompress') && ($decoded = @gzuncompress($data)) !== false) {
740 * Decompression of deflated string while staying compatible with the majority of servers.
742 * Certain Servers will return deflated data with headers which PHP's gzinflate()
743 * function cannot handle out of the box. The following function has been created from
744 * various snippets on the gzinflate() PHP documentation.
746 * Warning: Magic numbers within. Due to the potential different formats that the compressed
747 * data may be returned in, some "magic offsets" are needed to ensure proper decompression
748 * takes place. For a simple progmatic way to determine the magic offset in use, see:
749 * http://core.trac.wordpress.org/ticket/18273
752 * @link http://core.trac.wordpress.org/ticket/18273
753 * @link http://au2.php.net/manual/en/function.gzinflate.php#70875
754 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336
756 * @param string $gzData String to decompress.
757 * @return string|bool False on failure.
759 public static function compatible_gzinflate($gzData) {
760 // Compressed data might contain a full zlib header, if so strip it for
762 if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) {
764 $flg = ord( substr($gzData, 3, 1) );
767 list($xlen) = unpack('v', substr($gzData, $i, 2) );
771 $i = strpos($gzData, "\0", $i) + 1;
773 $i = strpos($gzData, "\0", $i) + 1;
777 $decompressed = self::compatible_gzinflate( substr( $gzData, $i ) );
778 if ( false !== $decompressed ) {
779 return $decompressed;
783 // If the data is Huffman Encoded, we must first strip the leading 2
784 // byte Huffman marker for gzinflate()
785 // The response is Huffman coded by many compressors such as
786 // java.util.zip.Deflater, Ruby’s Zlib::Deflate, and .NET's
787 // System.IO.Compression.DeflateStream.
789 // See http://decompres.blogspot.com/ for a quick explanation of this
791 $huffman_encoded = false;
793 // low nibble of first byte should be 0x08
794 list( , $first_nibble ) = unpack( 'h', $gzData );
796 // First 2 bytes should be divisible by 0x1F
797 list( , $first_two_bytes ) = unpack( 'n', $gzData );
799 if ( 0x08 == $first_nibble && 0 == ( $first_two_bytes % 0x1F ) )
800 $huffman_encoded = true;
802 if ( $huffman_encoded ) {
803 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 2 ) ) ) )
804 return $decompressed;
807 if ( "\x50\x4b\x03\x04" == substr( $gzData, 0, 4 ) ) {
808 // ZIP file format header
809 // Offset 6: 2 bytes, General-purpose field
810 // Offset 26: 2 bytes, filename length
811 // Offset 28: 2 bytes, optional field length
812 // Offset 30: Filename field, followed by optional field, followed
813 // immediately by data
814 list( , $general_purpose_flag ) = unpack( 'v', substr( $gzData, 6, 2 ) );
816 // If the file has been compressed on the fly, 0x08 bit is set of
817 // the general purpose field. We can use this to differentiate
818 // between a compressed document, and a ZIP file
819 $zip_compressed_on_the_fly = ( 0x08 == (0x08 & $general_purpose_flag ) );
821 if ( ! $zip_compressed_on_the_fly ) {
822 // Don't attempt to decode a compressed zip file
826 // Determine the first byte of data, based on the above ZIP header
828 $first_file_start = array_sum( unpack( 'v2', substr( $gzData, 26, 4 ) ) );
829 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 30 + $first_file_start ) ) ) ) {
830 return $decompressed;
835 // Finally fall back to straight gzinflate
836 if ( false !== ( $decompressed = @gzinflate( $gzData ) ) ) {
837 return $decompressed;
840 // Fallback for all above failing, not expected, but included for
841 // debugging and preventing regressions and to track stats
842 if ( false !== ( $decompressed = @gzinflate( substr( $gzData, 2 ) ) ) ) {
843 return $decompressed;
849 public static function match_domain($host, $reference) {
850 // Check for a direct match
851 if ($host === $reference) {
855 // Calculate the valid wildcard match if the host is not an IP address
856 // Also validates that the host has 3 parts or more, as per Firefox's
858 $parts = explode('.', $host);
859 if (ip2long($host) === false && count($parts) >= 3) {
861 $wildcard = implode('.', $parts);
862 if ($wildcard === $reference) {