简体   繁体   中英

I'm trying to pass HTTP_X_FORWARDED_FOR in header to php server but not getting its value in server

I setup following php script on first server to print all server values

var_dump($_SERVER)

from another server calling first server link

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => FIRST_SERVER_URL,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => array(
    "HTTP_X_FORWARDED_FOR: 111.90.148.19",
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

But I'm not getting value of HTTP_X_FORWARDED_FOR in $_SERVER values

I tried javascript like this.

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", FIRST_SERVER_URL);
xhr.setRequestHeader("HTTP_X_FORWARDED_FOR", "111.90.148.19");    
xhr.send(data);

You should set the header name in JS according to HTTP rules, not PHP internal name. The header name is actually:

X-Forwarded-For

So your JS code should be like this:

...
xhr.setRequestHeader("X-Forwarded-For", "111.90.148.19");
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM