• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Solved Auto-detect country when accessing register.php

johnsamir

Advanced OT User
Joined
Oct 13, 2009
Messages
1,126
Solutions
6
Reaction score
198
Location
Nowhere
Hello

I use ZnoteAcc 1.5
Would like that when a player access to register section it would auto detect his country and will choose it right away, if would be possible to make that country the only available option would be cool
so what i've done so far is this
check_country.php
Lua:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once '../../engine/init.php';
require_once '../../engine/function/users.php';
require_once dirname(__FILE__) . '/../../config.countries.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/config.countries.php';
//require_once '../../engine/init.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/init.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/function/users.php';
//require_once '../../engine/function/users.php';
//require_once '../../engine/function/users.php';
//require_once 'config.countries.php'; // Adjust the path if necessary
//require_once $_SERVER['DOCUMENT_ROOT'] . '/config.countries.php';

// Get the user's public IP address
$user_ip = file_get_contents('https://api.ipify.org');

// Fetch the user's location data from ip-api.com
$ipapi_url = "http://ip-api.com/json/$user_ip";
echo "API URL: $ipapi_url"; // Echo the URL for debugging

$location_data = file_get_contents($ipapi_url);

if ($location_data === false) {
    $response = ['error' => 'Unable to fetch location data'];
} else {
    $location_data = json_decode($location_data, true);
    $country_code = $location_data['countryCode'] ?? ''; // Default to empty string if not found
    $response = [];
    // Validate if the country code exists in your countries config
    if (!empty($country_code) && isset($config['countries'][strtolower($country_code)])) {
        $response['country_code'] = strtolower($country_code);
        $response['country_name'] = $config['countries'][strtolower($country_code)];
    } else {
        // If country code is not found or invalid, return an error
        $response['error'] = 'Unable to detect your country';
    }
}

header('Content-Type: application/json');
echo json_encode($response);

?>
located at
Code:
C:\xampp\htdocs\layout\sub
then in register.php located at
Code:
C:\xampp\htdocs
added this script

Code:
$(document).ready(function(){
    // Function to get user's country based on IP
    function getUserCountry() {
        $.ajax({
            url: 'check_country.php',
            type: 'GET',
            success: function(response) {
                if (response.country_code) {
                    // Add an option for the detected country
                    $('#countrySelect').append('<option value="' + response.country_code + '" selected="selected">' + response.country_name + '</option>');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
            }
        });
    }

    // Call the function to get user's country on page load
    getUserCountry();
});
</script>
and i changed country filling form from this
Code:
<!-- Rest of your form fields -->

                  <b>Country:<br></b>
        <select name="flag">
            <option value="">(Please choose)</option>
            <?php
            foreach(array('pl', 'se', 'br', 'us', 'gb', ) as $c)
                echo '<option value="' . $c . '">' . $config['countries'][$c] . '</option>';

                echo '<option value="">----------</option>';
                foreach($config['countries'] as $code => $c)
                    echo '<option value="' . $code . '">' . $c . '</option>';
            ?>
        </select>
            </li>
to this

Code:
 <li>
    <!-- Rest of your form fields -->
    <b>Country:<br></b>
    <select name="flag" id="countrySelect">
        <option value="">(Please choose)</option>
    </select>
</li>
no errors directly in console but if i press f12 i get all these errors
Code:
jquery-1.10.2.min.js:8706
 GET http://127.0.0.1/check_country.php 404 (Not Found)
send    @    jquery-1.10.2.min.js:8706
ajax    @    jquery-1.10.2.min.js:8136
getUserCountry    @    register.php:494
(anonymous)    @    register.php:510
fire    @    jquery-1.10.2.min.js:3048
fireWith    @    jquery-1.10.2.min.js:3160
ready    @    jquery-1.10.2.min.js:433
completed    @    jquery-1.10.2.min.js:104
register.php:504 Error: Not Found
error    @    register.php:504
fire    @    jquery-1.10.2.min.js:3048
fireWith    @    jquery-1.10.2.min.js:3160
done    @    jquery-1.10.2.min.js:8237
callback    @    jquery-1.10.2.min.js:8778
XMLHttpRequest.send (async)      
send    @    jquery-1.10.2.min.js:8706
ajax    @    jquery-1.10.2.min.js:8136
getUserCountry    @    register.php:494
(anonymous)    @    register.php:510
fire    @    jquery-1.10.2.min.js:3048
fireWith    @    jquery-1.10.2.min.js:3160
ready    @    jquery-1.10.2.min.js:433
completed    @    jquery-1.10.2.min.js:104
34
Third-party cookie will be blocked. Learn more in the

i already have jquery-1.10.2.min.js installed in C:\xampp\htdocs\engine\js and in C:\xampp\htdocs\layout too
also i checked check_country.php via browser and seems to be working http://127.0.0.1/layout/sub/check_country.php
API URL: http://ip-api.com/json/152.172.xxx.246{"country_code":"xl","country_name":"China"}

can somebody lend me a hand?
 
What exactly isn't working? Your threads are very confusing.

Once again, best thing to do is to log the response.
After:
JavaScript:
success: function(response) {
Add:
JavaScript:
console.log(response)
 
You don't need jquery for this at all.

Just paste the code above that form and use it in that <select with "selected" attribute.
don't want to select it i want to remove the array in first place and make to autodeted user country to make it the only available option in the list, so player wont be able to change location easily at least
Post automatically merged:

What exactly isn't working? Your threads are very confusing.

Once again, best thing to do is to log the response.
After:
JavaScript:
success: function(response) {
Add:
JavaScript:
console.log(response)
everything seems to be working now
if i go here
Lua:
http://127.0.0.1/layout/sub/check_country.php
i get the info
now in register.php have added this script
Code:
<!-- <script> -->
                <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
                <!-- <script src="https://cdn.jsdelivr.net/npm/slidesjs@3/dist/jquery.slides.min.js"></script> -->
                <script src="https://cdnjs.cloudflare.com/ajax/libs/slidesjs/3.0/jquery.slides.min.js"></script>
<script>
    $(document).ready(function(){
    // Function to get user's country based on IP
    function getUserCountry() {
        $.ajax({
            url: 'layout/sub/check_country.php', // Update the URL here
            type: 'GET',
            success: function(response) {
                if (response.country_code) {
                    // Add an option for the detected country and select it by default
                    $('#countrySelect').html('<option value="' + response.country_code + '" selected="selected">' + response.country_name + '</option>');
                } else {
                    // If country code is not detected, display a default option
                    $('#countrySelect').html('<option value="">(Country detection failed, please select)</option>');
                }
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
                // If an error occurs during detection, display a default option
                $('#countrySelect').html('<option value="">(Country detection failed, please select)</option>');
            }
        });
    }

    // Call the function to get user's country on page load
    getUserCountry();
});
filling form now looks like this
Code:
 <li>
    Rest of your form fields
    <b>Country:<br></b>
<select name="flag" id="countrySelect">
    <option value="">(Please wait, detecting your country...)</option>
</select>
</li>
in register.php if i press f12 i get this error
Code:
register.php:373 Error: SyntaxError: Unexpected token 'A', "API URL: h"... is not valid JSON
    at parse (<anonymous>)
    at jquery-3.6.0.min.js:2:79470
    at l (jquery-3.6.0.min.js:2:79587)
    at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2:82355)
@Fjorda
check_country.php looks like this
Lua:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once '../../engine/init.php';
require_once '../../engine/function/users.php';
require_once dirname(__FILE__) . '/../../config.countries.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/config.countries.php';
//require_once '../../engine/init.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/init.php';
//require_once $_SERVER['DOCUMENT_ROOT'] . '/engine/function/users.php';
//require_once '../../engine/function/users.php';
//require_once '../../engine/function/users.php';
//require_once 'config.countries.php'; // Adjust the path if necessary
//require_once $_SERVER['DOCUMENT_ROOT'] . '/config.countries.php';

// Get the user's public IP address
$user_ip = file_get_contents('https://api.ipify.org');

// Fetch the user's location data from ip-api.com
$ipapi_url = "http://ip-api.com/json/$user_ip";
echo "API URL: $ipapi_url"; // Echo the URL for debugging

$location_data = file_get_contents($ipapi_url);

if ($location_data === false) {
    $response = ['error' => 'Unable to fetch location data'];
} else {
    $location_data = json_decode($location_data, true);
    $country_code = $location_data['countryCode'] ?? ''; // Default to empty string if not found
    $response = [];
    // Validate if the country code exists in your countries config
    if (!empty($country_code) && isset($config['countries'][strtolower($country_code)])) {
        $response['country_code'] = strtolower($country_code);
        $response['country_name'] = $config['countries'][strtolower($country_code)];
    } else {
        // If country code is not found or invalid, return an error
        $response['error'] = 'Unable to detect your country';
    }
}

header('Content-Type: application/json');
echo json_encode($response);

?>

full error in register.php by pressing f12

Code:
register.php:373 Error: SyntaxError: Unexpected token 'A', "API URL: h"... is not valid JSON
    at parse (<anonymous>)
    at jquery-3.6.0.min.js:2:79470
    at l (jquery-3.6.0.min.js:2:79587)
    at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2:82355)
error @ register.php:373
c @ jquery-3.6.0.min.js:2
fireWith @ jquery-3.6.0.min.js:2
l @ jquery-3.6.0.min.js:2
(anonymous) @ jquery-3.6.0.min.js:2
register.php:479 Response: {exists: true}
Post automatically merged:

Solved!
in register.php changed to
Code:
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    <!-- SlidesJS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/slidesjs/3.0/jquery.slides.min.js"></script>
<script>
 $(document).ready(function() {
            // Your existing code

            // Initialize SlidesJS
            $("#slides").slidesjs({
                width: 940,
                height: 528,
                play: {
                    active: true,
                    auto: true,
                    interval: 4000,
                    swap: true
                }
            });

            // Function to get user's country based on IP
            function getUserCountry() {
                $.ajax({
                    url: 'layout/sub/check_country.php', // Updated to the correct path
                    type: 'GET',
                    success: function(data) {
                        console.log('Response:', data); // Log the response data

                        // No need to parse the response, it's already a JSON object
                        if (data.country_code) {
                            // Add an option for the detected country and select it by default
                            $('#countrySelect').html('<option value="' + data.country_code + '" selected="selected">' + data.country_name + '</option>');
                        } else {
                            // If country code is not detected, display a default option
                            $('#countrySelect').html('<option value="">(Country detection failed, please select)</option>');
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('Error:', error);
                        // If an error occurs during detection, display a default option
                        $('#countrySelect').html('<option value="">(Country detection failed, please select)</option>');
                    }
                });
            }

            // Call the function to get user's country on page load
            getUserCountry();
        });
 
Last edited:
Back
Top