-1

This is in my php page

// Change the line below to your timezone!
date_default_timezone_set('Asia/Manila');
$date = date('m/d/Y h:i:s a', time());
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
  $ip=$_SERVER['HTTP_CLIENT_IP'];}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
  $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];}
else{
  $ip=$_SERVER['REMOTE_ADDR'];}
//print json_encode(array('ip' => $ip));

//echo $date;

echo json_encode(array(
    'date' => $date,
    'ip' => $ip
));

This is in my ajax

var currentservertime = "";
var clientip = "";
$.ajax({
    url: '../currenttime.php',
    type: 'POST',
    dataType: "json",
    success: function(data) {
        currentservertime = data.date;
        clientip = data.ip;

    },
    error: function(data) {
        var message = "Error Occured!";
        $("#dialog").html(message);
        $("#dialog").dialog({
            title: dialogtitle
        });
        $("#dialog").dialog("open");
    }
});

Then I have console.log(clientip) in a button click it out puts

::1

In console. Why is this the IP that I am getting in PHP page.

The sample I followed is found here

Community
  • 1
  • 1
Brownman Revival
  • 3,620
  • 9
  • 31
  • 69

3 Answers3

1

Because you are using localhost that means https://localhost/sitename.

But if you access your localhost from other PC by your system IP then it will show you the IP of other PC

d.coder
  • 1,988
  • 16
  • 23
0

You get ::1 cause you're using localhost host as explained here :

IP Address of the machine in PHP gives ::1 but why?

Community
  • 1
  • 1
Nirnae
  • 1,315
  • 11
  • 23
0

From localhost you will get your ip address only that is ::1 For get your internet ip address from your local machine then you have to make change in your PHP script, IF ip not found or not valid then you have to use third party API.

// Change the line below to your timezone!
date_default_timezone_set('Asia/Manila');
$date = date('m/d/Y h:i:s a', time());
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
    $ip=$_SERVER['REMOTE_ADDR'];
}

if(empty($ip) || $ip=="::1" || $ip=="127.0.0.1")
{
    $ip = file_get_contents('http://api.ipify.org');
}
//print json_encode(array('ip' => $ip));

//echo $date;

echo json_encode(array(
'date' => $date,
'ip' => $ip
));
Haresh Vidja
  • 8,340
  • 3
  • 25
  • 42