Gospel. Culture. Technology. Music.

Tag: code


WordPress, User IP’s and Reverse Proxies

Apparently there is no code yet in WordPress to get a users’ IP address when running the web server behind a web proxy. So I hacked my own in. This seems to be a not-too-common problem, but it may help some people. I have a solution that works, but it requires some extra code and changes to the existing code. It differentiates between a web user hitting the web server directly (as in most hosting situations, or through a transparent proxy) or hitting the web server through a reverse proxy (as in my situation). I wrote this code a year ago for another site I own that runs behind an Apache reverse proxy I run at home.

PHP Code for Remote IP Address Detection on a Web Page

I wrote this code today to return the IP address of a remote host when either the host hits the web server directly or accesses it through a web proxy (as in my situation). Thought someone might find it useful.

function writeIPAddress() {
if (isset($_SERVER[‘HTTP_X_FORWARDED_FOR’]) == ”) {
return $_SERVER[‘REMOTE_ADDR’];
}

else {
return $_SERVER[‘HTTP_X_FORWARDED_FOR’];
}
}

Then, if you want to return the IP address as text on the page, simply do this:

echo writeIPAddress();

In addition, if you want to return the reverse DNS address of the IP, do this:

echo @gethostbyaddr(writeIPAddress());

Powered by WordPress & Theme by Anders Norén