vin
vin

Reputation: 562

How to Auto select User's country in registration form's select menu using PHP?

How can get users country by default selected in my select box when he use my application from his location?

In javascript or php?

Please help me.

Thanks in Advance.

Upvotes: 0

Views: 2509

Answers (1)

dstonek
dstonek

Reputation: 975

1) Download this database and extract the csv file https://sourceforge.net/projects/bowlfish/files/Others/ip2country/ip-to-country.csv.zip/download
Create a mysql table "country_codes" at "DBname" database with 5 columns "ip_from" (bigint 20), "ip_to" (bigint 20), country_code2 (char 3), country_code3 (char 3), country_name (varchar 50) and import the csv file.

2) create a file country.php with

$ip = $_SERVER['REMOTE_ADDR'];

// Establishing a database connection
$dbh=mysql_connect("localhost","DBuser","DBpsw");
mysql_select_db("DBname");


// Query for getting visitor countrycode
$country_query  = "SELECT country_code2,country_name FROM country_codes ".
     "WHERE ip_from <= inet_aton('$ip') ".
      "AND ip_to >= inet_aton('$ip') ";


// 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);


?>

3) include_once 'country.php'; in you form file and use $country_name

Upvotes: 1

Related Questions