$value) { $url .= $sep . $key . "=" . urlencode($value); $sep = '&'; } // Send back the right method $method = $_SERVER['REQUEST_METHOD']; /* * Common awaited Content-Type header values: * - Content-Type: text/html * - Content-Type: application/x-www-form-urlencoded * - Content-Type: multipart/form-data * - Content-Type: application/xml * The fact is, whatever sends the remote client, if this header is present we * must send back data, which we get back. */ if (isset($_SERVER['CONTENT_TYPE']) && ! empty($_SERVER['CONTENT_LENGTH'])) { // Get back the correct data $headers['Content-Type'] = $_SERVER['CONTENT_TYPE']; $headers['Content-Length'] = $_SERVER['CONTENT_LENGTH']; $data = @file_get_contents('php://input'); } else { $data = NULL; } // Proxy request should pass on cookie headers to prevent Drupal from // ending a session. Note: only if same host as this site! if (!empty($_COOKIE) && $_SERVER['HTTP_HOST'] == parse_url($url, PHP_URL_HOST)) { $cookies = ''; $sep = ''; foreach ($_COOKIE as $key => $value) { $cookies .= $sep . $key . '=' . $value; $sep = '; '; } $headers['Cookie'] = $cookies; } $response = proxy_stream_request($url, $headers, $method, $data); exit(); /** * Perform an HTTP request. * * This is a flexible and powerful HTTP client implementation. Correctly handles * GET, POST, PUT or any other HTTP requests. Handles redirects. * * @param $url * A string containing a fully qualified URI. * @param $headers * An array containing an HTTP header => value pair. * @param $method * A string defining the HTTP request to use. * @param $data * A string containing data to include in the request. * @param $retry * An integer representing how many times to retry the request in case of a * redirect. * @return * An object containing the HTTP request headers, response code, headers, * data and redirect status. */ function proxy_stream_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) { // Better in a static variable static $responses = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported' ); // Prepare new object $result = new stdClass(); $result->headers = array(); $result->data = NULL; // Temporary header variable, which we won't display in case we have to retry $fullheader = ''; // Parse the URL and make sure we can handle the schema. $uri = parse_url($url); switch ($uri['scheme']) { case 'http': $port = isset($uri['port']) ? $uri['port'] : 80; $host = $uri['host'] . ($port != 80 ? ':'. $port : ''); $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15); break; case 'https': // Note: Only works for PHP 4.3 compiled with OpenSSL. $port = isset($uri['port']) ? $uri['port'] : 443; $host = $uri['host'] . ($port != 443 ? ':'. $port : ''); $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20); break; default: $result->error = 'invalid schema '. $uri['scheme']; return $result; } // Make sure the socket opened properly. if (!$fp) { // When a network error occurs, we use a negative number so it does not // clash with the HTTP status codes. $result->code = -$errno; $result->error = trim($errstr); return $result; } // Construct the path to act on. $path = isset($uri['path']) ? $uri['path'] : '/'; if (isset($uri['query'])) { $path .= '?'. $uri['query']; } // Create HTTP request. $defaults = array( // RFC 2616: "non-standard ports MUST, default ports MAY be included". // We don't add the port to prevent from breaking rewrite rules checking the // host that do not take into account the port number. 'Host' => "Host: $host", 'User-Agent' => 'User-Agent: Mapping proxy', 'Content-Length' => 'Content-Length: '. strlen($data) ); // If the server url has a user then attempt to use basic authentication if (isset($uri['user'])) { $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : '')); } foreach ($headers as $header => $value) { $defaults[$header] = $header .': '. $value; } $request = $method .' '. $path ." HTTP/1.0\r\n"; $request .= implode("\r\n", $defaults); $request .= "\r\n\r\n"; if ($data) { $request .= $data ."\r\n"; } $result->request = $request; fwrite($fp, $request); // Get first line of HTTP response in order to parse header correctly. if (!feof($fp) && $chunk = fgets($fp)) { list($protocol, $code, $text) = explode(' ', trim($chunk), 3); $fullheader .= $chunk; } // First pass, sequential reading until we get all HTTP headers, in order to // parse them. do { if (preg_match('/^[\n\r\s]*$/', $chunk)) { // Stop sequential reading when the buffer is an empty line, it means that // we got all the HTTP headers break; } // Parse HTTP header line list($header, $value) = explode(':', $chunk, 2); if (isset($result->headers[$header]) && $header == 'Set-Cookie') { // RFC 2109: the Set-Cookie response header comprises the token Set- // Cookie:, followed by a comma-separated list of one or more cookies. $result->headers[$header] .= ',' . trim($value); } else { $result->headers[$header] = trim($value); } // Begin to display reponse $fullheader .= $chunk; } while (!feof($fp) && $chunk = fgets($fp)); // RFC 2616 states that all unknown HTTP codes must be treated the same as the // base code in their class. if (!isset($responses[$code])) { $code = floor($code / 100) * 100; } if ($code == '200' || $code == '304') { // We have a success return code, we are going to display full header and // stream data. ob_start(); print $fullheader; print "\n"; // Data stream do { flush(); ob_flush(); $result->data .= $chunk; print $chunk; } while (!feof($fp) && $chunk = fread($fp, 512)); flush(); ob_end_flush(); fclose($fp); } else { // Close handle because we are making a new request fclose($fp); // What should we do? switch ($code) { case 301: case 302: case 307: $location = $result->headers['Location']; if ($retry) { $result = proxy_request($result->headers['Location'], $headers, $method, $data, --$retry); $result->redirect_code = $result->code; } $result->redirect_url = $location; break; default: $result->error = $text; } } $result->code = $code; return $result; }