Reputation: 2085
I have this PHP function that logs the visitors to a .txt
file (for security reasons). It uses an API to get their location. It works fine on localhost
, but when it's actually live it logs empty values. I'm assuming it's because the functions runs before the API has had time to return the data. Is there a way to write something like a Javascript promise
or some asynchronous function that will wait for the data to return before logging it?
This is what I currently have:
function getLocation() {
$query = @unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
$user = $_SERVER['REMOTE_ADDR'].' - '.date("H:i:s d-m-Y").' - '.$query['country'].', '.$query['regionName'].', '.$query['city'].', '.$query['zip'];
$file = '../logs/userlog.txt';
$currentFileData = file_get_contents($file);
$currentFileData .= $user . PHP_EOL;
file_put_contents($file, $currentFileData);
}
}
What the output should be:
127.0.0.1 - 11:59:33 03-04-2020 - South Africa, Western Cape, Cape Town, 8001
What the actual output is:
127.0.0.1 - 11:59:33 03-04-2020 - , , ,
Your help will be greatly appreciated!
Upvotes: 0
Views: 147
Reputation: 2085
SOLVED: Thanks to @DanielProtopopov's post I actually found on the documentation that this php
version of the API has been deprecated. So using @DanielProtopopov's fix I have to use the JSON API for it to work:
$query = json_decode(file_get_contents('http://ip-api.com/json/' . $_SERVER['REMOTE_ADDR']));
Upvotes: 0
Reputation: 7236
You are not passing the IP address as stated in the documentation after the /php/ part of the URL. It should be
$query = @unserialize (file_get_contents('http://ip-api.com/php/' . $_SERVER['REMOTE_ADDR']));
Upvotes: 3