My site has a few thousand pages on which I use a php include to place ads. I want to do geoloc. Got the db and using this code to geoloc: <?php include("geoip.inc"); // include the geoip functions $geofile = geoip_open("GeoIP.dat",GEOIP_STANDARD); // open geoip data file $cc = geoip_country_code_by_addr($geofile, $_SERVER['REMOTE_ADDR']); geoip_close($geofile); // close the data file if($cc == "US") { echo "<ad for US visitors>"; } // end if US else { echo "<ad for non-US visitors>"; } PHP: Works great when I invoke it directly. But when include it via the php include in the webpages it gets the IP of my web server, not the IP of the visitor. What am I doing wrong?
Swap: $cc = geoip_country_code_by_addr($geofile, $_SERVER['REMOTE_ADDR']); PHP: With: $cc = geoip_country_code_by_addr($geofile, $ip); PHP: And add this to the top of the include: if (isset($_SERVER)) { if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } else { $ip = $_SERVER['REMOTE_ADDR']; } } else { if (getenv('HTTP_X_FORWARDED_FOR')) { $ip = getenv('HTTP_X_FORWARDED_FOR'); } elseif (getenv('HTTP_CLIENT_IP')) { $ip = getenv('HTTP_CLIENT_IP'); } else { $ip = getenv('REMOTE_ADDR'); } } PHP: BTW you should stick it all in a cookie so you don;t have to query the DB file every impression.
Do as TOP said, except place the last snippet before you include the file (e.g.: main file) then pass the IP as a variable. Peace,
Currently each page has this: <?php include('path-to-geloc-ad.php'); ?> What's the syntax to pass the IP as a variable?
You guys are goooood. It works - thanks so much. The only troublesome part is I have to go and make that change to the include on every page. I'll go off now and tinker with a script to automate that.
This solution works great. But... I discovered an interesting problem yesterday. I checked my website from another location and I got a php error messages that showed the IP that was passed was of the form xxx.xxx.xxx.xxx, xxx.xxx.xxx.xxx i.e. two IP addresses separated by a comma. Works fine from everywhere else I check it and my error log is clean except for a few errors like this. What's up with this?