0

I have the following curl code:

$url    = "https://example.com/api/blah/";
$result = remoteRequest ($url, 'POST', $postValues, true, true, array("X-Forwarded-For: $_SERVER[REMOTE_ADDR]"));

with the main function being:

function remoteRequest ($url, $type='POST', $postValues=array(), $json=true, $parseResponse=true, $extraHeaders=array())
{
    $curl = curl_init ($url);

    $postValuesString = '';
    if ($json && $postValues) {
        $postValuesString = json_encode ($postValues);
    }

    curl_setopt ($curl, CURLOPT_TIMEOUT, 3);
    curl_setopt ($curl, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true);

    if ($extraHeaders) {
        curl_setopt ($curl, CURLOPT_HTTPHEADER, $extraHeaders);
    }

    if ($type == 'POST') {
        curl_setopt ($curl, CURLOPT_POST, 1);
    }

    if ($postValues || $postValuesString) {
        curl_setopt ($curl, CURLOPT_POSTFIELDS, $postValuesString ? $postValuesString : $postValues);
    }

    if ($json) {
        if ($type == 'POST') {
            curl_setopt ($curl, CURLOPT_CUSTOMREQUEST, "POST");
        }
        curl_setopt ($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                                                      'Content-Length: ' . strlen($postValuesString)));
    }

    $rc = curl_exec ($curl);
    curl_close ($curl);

    return $rc;

}

I've tried everything I can think of, but the extra headers (x-forwarded-for) are simply not included in the request header.

I've verified this through some debug code as well as routing the curl request through squid and taking a look at it's log file.

Does anybody know what I'm doing wrong and what I have to do in order to get the x-forwarded-for header added to my request? I've even started wondering whether this could be related to me accessing a https (rather than http) URL but I'm guessing it's probably something else.

For the record, I'm using 5.6.9-1+deb.sury.org~trusty+2 on Ubunty 14.04.

2
  • I think problem with https protocol. Referrer this link it will helps you stackoverflow.com/questions/4372710/php-curl-https Commented Jun 27, 2015 at 1:59
  • This's my class based on curl,it supports multi-http(s)-request including get and post,also supports server proxy: ) iHttp Commented Jun 27, 2015 at 4:49

1 Answer 1

2

Probably because you're setting CURLOPT_HTTPHEADER again later in the code

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I can't believe the solution is this simple. I've been staring at this for hours and never even considered that this might be the problem. It now works like a charm.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.