Example #1
0
function makeRequest($url)
{
    //Tell cURL to make the request using the brower's user-agent if there is one, or a fallback user-agent otherwise.
    $user_agent = $_SERVER["HTTP_USER_AGENT"];
    if (empty($user_agent)) {
        $user_agent = "Mozilla/5.0 (compatible; miniProxy)";
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
    //Get ready to proxy the browser's request headers...
    $browserRequestHeaders = getallheaders();
    //...but let cURL set some headers on its own.
    removeKeys($browserRequestHeaders, array("Host", "Content-Length", "Accept-Encoding"));
    curl_setopt($ch, CURLOPT_ENCODING, "");
    //Transform the associative array from getallheaders() into an
    //indexed array of header strings to be passed to cURL.
    $curlRequestHeaders = array();
    foreach ($browserRequestHeaders as $name => $value) {
        $curlRequestHeaders[] = $name . ": " . $value;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curlRequestHeaders);
    //Proxy any received GET/POST/PUT data.
    switch ($_SERVER["REQUEST_METHOD"]) {
        case "POST":
            curl_setopt($ch, CURLOPT_POST, true);
            //For some reason, $HTTP_RAW_POST_DATA isn't working as documented at
            //http://php.net/manual/en/reserved.variables.httprawpostdata.php
            //but the php://input method works. This is likely to be flaky
            //across different server environments.
            //More info here: http://stackoverflow.com/questions/8899239/http-raw-post-data-not-being-populated-after-upgrade-to-php-5-3
            curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents("php://input"));
            break;
        case "PUT":
            curl_setopt($ch, CURLOPT_PUT, true);
            curl_setopt($ch, CURLOPT_INFILE, fopen("php://input"));
            break;
    }
    //Other cURL options.
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    //Set the request URL.
    curl_setopt($ch, CURLOPT_URL, $url);
    //Make the request.
    $response = curl_exec($ch);
    $responseInfo = curl_getinfo($ch);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    //Setting CURLOPT_HEADER to true above forces the response headers and body
    //to be output together--separate them.
    $responseHeaders = substr($response, 0, $headerSize);
    $responseBody = substr($response, $headerSize);
    return array("headers" => $responseHeaders, "body" => $responseBody, "responseInfo" => $responseInfo);
}
function removeKeys(array $array)
{
    $array = array_values($array);
    foreach ($array as &$value) {
        if (is_array($value)) {
            $value = removeKeys($value);
        }
    }
    return $array;
}