Get country code from JavaScript to PHP

Discuss coding issues, and scripts related to PHP and MySQL.
User avatar
JanMolendijk
Posts: 282
Location: Holland Rotterdam

Get country code from JavaScript to PHP

Chief I have a problem to get the countrycode into my sql-statement.

Please help me out....

This script is to detect the countrycode

Code: Select all

     <SCRIPT LANGUAGE="JavaScript1.2">
<!--
if (navigator.appName == 'Netscape')
var language = navigator.language;
else
var language = navigator.browserLanguage;

function writeMessage() { 
if (language.indexOf('en') > -1) document.write('US');
else if (language.indexOf('nl') > -1) document.write('NL');
else document.write('');
}

//  End -->
</script>

 <script>writeMessage();</script>
I try with this simple php code to detect $country_code1

Code: Select all

<?php

$country_code1 = '<script>writeMessage();</script>';

?>
This $country_code1 i try to get the result into this sql-document

Code: Select all

<?php
// connect to the "tests" database
$conn = new mysqli('127.0.0.1', 'ip_ban', '123456', 'ip_ban');
// check connection
if (mysqli_connect_errno()) {
  exit('Connect failed: '. mysqli_connect_error());
}
// SELECT sql query
$sql = "SELECT `ip_adress`, `country_code` FROM `ip_ban` WHERE ip_adress='$ip' or country_code='$country_code1' LIMIT 1  "; 
// perform the query and store the result
$result = $conn->query($sql);
// if the $result contains at least one row
if ($result->num_rows > 0) {
  // output data of each row from $result
  while($row = $result->fetch_assoc()) {
    echo ' <p> '. $row['ip_adress']. '   '. $row['country_code']. '
Your Banned
 <br>' ;
  }
}
else {
  echo '';
}
$conn->close();
?>


Admin Posts: 805
The JavaScript code cannot be executed in php.
Javascript is executed in browser, after the php finished to output its data.
Also, Javascript it is not suitable to get the user's country code because the country code can be determined by IP but your JS script reads the browser's language.

To get the country code with javascript you need to use ajax and a third party application, or an IP-to-location service (like: //ip-api.io/ or //maxmind.com/ ).
- Try look on the net for: "php get user country code".

Similar Topics