Forum Moderators: coopster
I am building a basic ad serving piece of software that needs to serve different ads across different countries. One of the requirements is to check the country the user is coming from, and based on the result serve an appropriate ad. The problem I have come into is that I found at [ip-to-country.webhosting.info...] that the IP ranges total 87,000+ records, which in turn would be pretty heavy to go through in a database to cross reference them against a user's IP every time I want to render an ad. Is there another way to do this, or is there some great free software that can be used to plug into a PHP app to perform this essential funtion?
Thanks in advance.
To reduce performance demands, try not to require country on the homepage / landing page. As soon as a visitor arrives on the homepage, start a background request and then cache the result. When they get to the page upon which you need the country, it's already ready and available immediately.
You can write the country and user's current IP to a cookie to avoid triggering a lookup twice; something like:
$cookiestring[]=ip2long($ip); //integer IP
$cookiestring[]=$countrycode; //the country code from lookup
$cookiestring[]=substr(md5("salt",implode("¦",$cookiestring),5,10); //a short hash of the first two + salt to stop meddling
set_cookie("geolocation",implode("¦",$cookiestring)...); //set expiry & domain as required Reading that again - just explode by ¦ - then test whether the hash part ([2]) matches a recalculation from [0] and [1].
exec("php /path/to/background_lookup.php $ip > /dev/null 2>&1 &"); i.e. start a background process with all output to /dev/null which does a lookup. Note the argument is a 'command line argument' to pass the IP.
1. Insert all IP records into db table
2. When page loads run query on ip table once to attain country
3. Store in geolocation cookie
..Upon return to site:
4. Check if cookie exists,
5. If it does, use that country
6. Else go back to step 2.
Seems like a simple but solid structure. Have I missed anything?