Solved

Geolocation with PHP and IP2Location.

Posted on 2009-07-05
23
507 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
23 Comments
 
LVL 10

Expert Comment

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

Expert Comment

by:szewkam
Comment Utility
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
Comment Utility
sorry a mispell in query ;). Line should look like:
$query = "SELECT * FROM IPCountry WHERE $ipno <= ipTO AND $ipno >= ipFROM";
0
 

Author Comment

by:chriskelly777
Comment Utility
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
Comment Utility
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
Comment Utility
hm...
are you sure that your script return right country code? Comment lines with header and echo variable countrySHORT.
0
 

Author Comment

by:chriskelly777
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 7

Expert Comment

by:szewkam
Comment Utility
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
Comment Utility
**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
Comment Utility
the table name is: ip2country and NOT: Table 'extremm8_ip2country.iptocountry' doesn't exist
0
 

Author Comment

by:chriskelly777
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
0
 

Author Comment

by:chriskelly777
Comment Utility
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
Comment Utility
this script work perfect for me: http://www.ip2nation.com/ thank you for your help anyway.
0
 

Author Comment

by:chriskelly777
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
"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
Comment Utility
Thank you for your help
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to dynamically set the form action using jQuery.

772 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now