Sorry if this is a noob question but I can't find a way to do this without the IP being cached;

I want to use the GeoIP information in my theme. I first tried using the API function in node.tpl.php but that got cached.

Then I tried to add the country code as a JSON object in template.php:
drupal_add_js(array('country' => geoip_country_code()), 'setting');

But that got cached too. Is there some sort of wrapper function that I can add, that prevents the country code from being cached?

Thx
JR

Comments

robdinardo’s picture

Title: exclude from cache? » same problem!

Hope this helps! In my page.tpl.php page I added this to the very top...

<?php 

	require_once("./sites/default/files/geoip/geoip.inc");
	geoip_load_shared_mem("./sites/default/files/geoip/GeoIP.dat");
	$gi = geoip_open("./sites/default/files/geoip/GeoIP.dat", GEOIP_STANDARD);
	
	$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
	$geoip->country_code = geoip_country_code_by_addr($gi, $ip);
	$geoip->country_name = geoip_country_name_by_addr($gi, $ip);
	$geoip->ipaddress = $ip;
	
	geoip_close($gi);
?>

then somewhere else on the same page (page.tpl.php) I can do something like:

<?php if($geoip->country_code == 'CA') { ?>
			Your IP is located in Canada 
<?php } ?>

This works if the caching is OFF. But if caching is ON, then it will use the value of the variable of the stored page and will only update if the caches are cleared (manually or auto by Drupal). Maybe the use of the GeoIP API module http://drupal.org/project/geoip is in order. But how do we use this module?

I have a related question: How do I use $geoip->country_code inside my nodes? Example: If I create new content (of type Page) how would I use $geoip->country_code? I tried it with this in the body field:

echo "country is = " . $geoip->country_code;

and I get: country is =

FYI - I did have Input Format set to PHP Code.

robdinardo’s picture

Title: same problem! » Geoip Caching Problem
drewish’s picture

Status: Active » Fixed

There's really not an easy way to use caching and have GeoIP work correctly. The best solution I can think of would be to use JavaScript to call back to the server asking for the client's country and then do replacements.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.