Solved

Geolocation with PHP and IP2Location.

Posted on 2009-07-05
23
536 Views
Last Modified: 2013-12-13
HI,

I'm trying to redirect user from one specific country to one html page and the rest to other html. I'm using with IP2Location.

The problem that I have is with PHP code.
I get this message error: "ip2country Query Failed" and I don't get redirect.

Any help will be really appreciated.
Line that show the error:
[PHP]<?php
	// Execute SQL query 
$result = mysql_query($query) or die("ip2country Query Failed"); 
 
?>[/PHP]
 
 
 
 
My DB name:extremm8_ip2country
the Table is:ip2country
User:8_admin
Pass:4Lobo
 
This is all the script:
[PHP]<?php 
// Replace this MYSQL server variables with actual configuration 
$mysql_server = "localhost"; 
$mysql_user_name = "8_admin"; 
$mysql_user_pass = "4Lobo"; 
 
// Retrieve visitor IP address from server variable REMOTE_ADDR 
$ipaddress = getenv(REMOTE_ADDR); 
 
// Convert IP address to IP number for querying database
$ipno = Dot2LongIP($ipaddress); 
 
// Connect to the database server 
$link = mysql_connect($mysql_server, $mysql_user_name, $mysql_user_pass) or die("Could not connect to MySQL database"); 
 
// Connect to the IP2Location database 
mysql_select_db("extremm8_ip2country") or die("Could not select database"); 
 
// SQL query string to match the recordset that the IP number fall between the valid range 
$query = "SELECT * FROM IPCountry WHERE $ipno < = ipTO AND $ipno>=ipFROM"; 
 
// Execute SQL query 
$result = mysql_query($query) or die("ip2country Query Failed"); 
 
// Retrieve the recordset (only one) 
$row = mysql_fetch_object($result); 
 
// Keep the country information into two different variables 
$countrySHORT = $row->countrySHORT; 
$countryLONG = $row->countryLONG; 
 
// Free recordset and close database connection 
mysql_free_result($result); mysql_close($link); 
 
// If the visitors are from JP, redirect them to JP site 
if ($countrySHORT == "CN") 
{
  Header("Location: http://www.google.co.jp"); 
} else { 
// Otherwise, redirect them to US site 
  Header("Location: http://www.google.com");
}
exit;
 
// Function to convert IP address (xxx.xxx.xxx.xxx) to IP number (0 to 256^4-1) 
function Dot2LongIP ($IPaddr) { 
 if ($IPaddr == "") 
 {
   return 0;
 } else { 
   $ips = split ("\.", "$IPaddr"); 
   return ($ips[3] + $ips[2] * 256 + $ips[1] * 256 * 256 + $ips[0] * 256 * 256 * 256); 
 }
} 
?> [/PHP]

Open in new window

0
Comment
Question by:chriskelly777
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
23 Comments
 
LVL 10

Expert Comment

by:jfromanski
ID: 24779222
What are ipTO and ipFROM, it looks that your $query has an error...
0
 
LVL 7

Expert Comment

by:szewkam
ID: 24779224
try changing line 36 from your snippet to
$query = "SELECT * FROM IPCountry WHERE $ipno <= ipTO AND $ipnoc >= ipFROM";
If that wouldn't help change line 39 to
$result = mysql_query($query) or die(mysql_error());
and paste here the error message
0
 
LVL 7

Expert Comment

by:szewkam
ID: 24779228
sorry a mispell in query ;). Line should look like:
$query = "SELECT * FROM IPCountry WHERE $ipno <= ipTO AND $ipno >= ipFROM";
0
SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

 

Author Comment

by:chriskelly777
ID: 24779280
szewkam: FROM IPCountry WHERE / FROM IP2Country WHERE

I don't have the error now but the redirection is not working properly. Now I'm in china and if I go to the page it send me to www.goggle.com that is for people in US . Which can be the problem?

// If the visitors are from CN - CHINA, redirect them to CN site
if ($countrySHORT == "CN")
{
  Header("Location: http://www.yahoo.com");
} else {
// Otherwise, redirect them to US site
  Header("Location: http://www.google.com");
}
exit;
0
 

Author Comment

by:chriskelly777
ID: 24779287
jfromanski:: It selects a range of IPs

look this is the place where I found the code:
http://www.ip2location.com/articles/article2.htm
0
 
LVL 7

Expert Comment

by:szewkam
ID: 24779405
hm...
are you sure that your script return right country code? Comment lines with header and echo variable countrySHORT.
0
 

Author Comment

by:chriskelly777
ID: 24779440
szewkam:
are you sure that your script return right country code?

I'm not sure. How we can test?

Please find in the attachment an image of how it looks the DB.
db.JPG
0
 
LVL 7

Expert Comment

by:szewkam
ID: 24779459
I explain it in my post ;)
But again, change this
// If the visitors are from CN - CHINA, redirect them to CN site
if ($countrySHORT == "CN")
{
  Header("Location: http://www.yahoo.com");
} else {
// Otherwise, redirect them to US site
  Header("Location: http://www.google.com");
}
exit; to this in snippet
But I may have another suggestion. Are you want to do just this comparison (i mean only redirection if the user is from china)? Because in that case it might be better not using mysql, just copy proper values and use it in script.
echo $countrySHORT;
// If the visitors are from CN - CHINA, redirect them to CN site
if ($countrySHORT == "CN")
{
  //Header("Location: http://www.yahoo.com");
} else {
// Otherwise, redirect them to US site
  //Header("Location: http://www.google.com");
}
//exit;

Open in new window

0
 

Author Comment

by:chriskelly777
ID: 24779500
If we can use the DB it will be the best because on the future I want to change and redirect user from US or other countries also the DB get updated every month with new IP ranges.

this is the DB in CSV format http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip in case you want to take a look.


I put your code and now the page stay don't redirect anywhere.
echo $countrySHORT;
// If the visitors are from CN - CHINA, redirect them to CN site
if ($countrySHORT == "CN")
{
  //Header("Location: http://www.yahoo.com");
} else {
// Otherwise, redirect them to US site
  //Header("Location: http://www.google.com");
}
//exit;

Open in new window

0
 

Author Comment

by:chriskelly777
ID: 24779522
For some reason the script "think" that I'm in USA but I'm in China. Maybe we can put your country on the script and check if the redirection works.

0
 

Author Comment

by:chriskelly777
ID: 24779548
now I'm trying this other code to see if it can show my Location

but I'm getting error on the line 25
   // Fetching the record set into an array
    $ccode_array=mysql_fetch_array($country_exec);
<?
 
    //---------------------------------------------------
    // Sample code to display Visitor Country information 
    // PHP 4 
    //---------------------------------------------------
 
 
    // Establishing a database connection
    $dbh=mysql_connect("localhost:3306","$MYSQL_USERNAME","$MYSQL_PASSWORD");
    mysql_select_db("$MYSQL_DBNAME");
 
 
    // Query for getting visitor countrycode
    $country_query  = "SELECT country_code2,country_name FROM iptoc ".
         "WHERE IP_FROM<=inet_aton('$REMOTE_ADDR') ".
          "AND IP_TO>=inet_aton('$REMOTE_ADDR') ";
 
 
    // Executing above query
    $country_exec = mysql_query($country_query);
 
 
    // Fetching the record set into an array
    $ccode_array=mysql_fetch_array($country_exec);
 
 
    // getting the country code from the array
    $country_code=$ccode_array['country_code2'];
 
 
    // getting the country name from the array
    $country_name=$ccode_array['country_name'];
 
 
   // Display the Visitor coountry information
   echo "$country_code - $country_name";
 
 
   // Closing the database connection
   mysql_close($dbh);
 
 
?>

Open in new window

0
 
LVL 7

Expert Comment

by:szewkam
ID: 24779647
first - after my update site won't redirect, but it will show the country code and you can check if it's correct;
second - could you submit link to site where you have this script. I could check if it shows my correct country code.
third - what error on the second script. You should change line 21 to $country_exec = mysql_query($country_query) or die (mysql_error());
because most probably cause of the error while fetching result set is error in statement
0
 

Author Comment

by:chriskelly777
ID: 24779715
**third - what error on the second script. You should change line 21 to $country_exec = mysql_query($country_query) or die (mysql_error());
----
http://69.89.31.83/~extremm8/test2.php
Table 'extremm8_ip2country.iptocountry' doesn't exist
----
**first - after my update site won't redirect, but it will show the country code and you can check if it's correct;
----
It only show a white page because the first scrip only redirects. The second script should be able to show your info but is not working.
----
second - could you submit link to site where you have this script. I could check if it shows my correct country code.
-----
http://69.89.31.83/~extremm8/test.php


0
 

Author Comment

by:chriskelly777
ID: 24779720
the table name is: ip2country and NOT: Table 'extremm8_ip2country.iptocountry' doesn't exist
0
 

Author Comment

by:chriskelly777
ID: 24779754
I make some changes in the code according to the DB.

Thank you for all your help.
// Query for getting visitor countrycode
  $country_query  = "SELECT country2,country FROM ip2country ".
       "WHERE ipFrom<=inet_aton('".$_ENV['REMOTE_ADDR']."') ".
        "AND ipTo>=inet_aton('".$_ENV['REMOTE_ADDR']."') ";
 
 
 
    // Executing above query
    $country_exec = mysql_query($country_query);
//$country_exec = mysql_query($country_query) or die (mysql_error());
 
    // Fetching the record set into an array
    $ccode_array=mysql_fetch_array($country_exec);
 
 
    // getting the country code from the array
    $country2=$ccode_array['country2'];
 
 
    // getting the country name from the array
    $country=$ccode_array['country'];
 
 
   // Display the Visitor coountry information
   echo "$country2 - $country";
 
 
   // Closing the database connection
   mysql_close($dbh);

Open in new window

0
 

Author Comment

by:chriskelly777
ID: 24779779
szewkam: If is easier to do lets put the ranges in the script. I want to redirect the people that come from USA to an specific page and the rest of the world to another page.
0
 
LVL 7

Accepted Solution

by:
szewkam earned 500 total points
ID: 24779794
glad we can help. I see that the second script works properly now, i get the right country code when i visit it :)
0
 

Author Comment

by:chriskelly777
ID: 24779802
0
 

Author Comment

by:chriskelly777
ID: 24779809
I crazy none of the two scripts work for me :(

this script show my location correctly: http://www.ip2nation.com/ and the other too but the one on the server don't show anything to me.
0
 

Author Comment

by:chriskelly777
ID: 24779851
this script work perfect for me: http://www.ip2nation.com/ thank you for your help anyway.
0
 

Author Comment

by:chriskelly777
ID: 24779871
how can I run this script ( http://www.ip2nation.com/ip2nation/Sample_Scripts/Country_Based_Redirect ) on every page of my website avoiding visitor form specific country to enter and I want to redirect them?

0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 24780008
"how can I run this script on every page of my website..."

That really seems like a different question.  I think szewkam answered the original question pretty well.

When you have something you want to run on every page of a web site, it is helpful to isolate the code and put it into some kind of a "config.php" file that you require_once() at the top of every page of the web site.

Best regards, ~Ray
0
 

Author Closing Comment

by:chriskelly777
ID: 31599887
Thank you for your help
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

734 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question