Add the Http_X_Forwarded_For header in a request in python

http-headers, php, python

Solution

The header should be `X-Forwarded-For` on the urllib (Python) side. Your webserver then reads that into the `HTTP_X_FORWARDED_FOR` environment variable which you read from `$_SERVER`.

opener.addheaders = [('X-Forwarded-For','1.2.3.4'),]

Problem

I have a small PHP code in a web server. The PHP code just logs the IP of the people that do a request with this line: ``` $ip = !empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']; echo 'Your IP is:'.$ip ``` I want to create a piece of code in Python that uses the `HTTP_X_FORWARDED_FOR` header to force the webserver to log other IP than the real one. I have written this code: ``` import urllib2,cookielib cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders = [('HTTP_X_FORWARDED_FOR','1.2.3.4'),] resp=opener.open('http://example.com/logIP.php') ``` Why doesn't the PHP code 1.2.3.4 if I have set it in my Python code? How can I force the web app to show the "fake" IP?

Original source