0

I have to get public IP of the remote system in php. I have tried

$_SERVER['REMOTE_ADDR'] getenv('REMOTE_ADDR'); 

but is always returning the private IP. Help to fix it.

3
  • Did you try $_SERVER["HTTP_X_FORWARDED_FOR"]? Commented Sep 4, 2015 at 6:14
  • 3
    possible duplicate of How to get the client IP address in PHP? Commented Sep 4, 2015 at 6:14
  • Ya i tried $_SERVER['HTTP_X_FORWARDED_FOR'] also @Michelem Commented Sep 4, 2015 at 6:24

2 Answers 2

1

Try this:

$ip = !empty($_SERVER['HTTP_CLIENT_IP']) ? $_SERVER['HTTP_CLIENT_IP'] : (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR']); 

Warning: you should extend it and sanitize, since headers can be easily manipulated.

Sign up to request clarification or add additional context in comments.

1 Comment

When i try $_SERVER["HTTP_X_FORWARDED_FOR"] in online phpfiddle it is returning the both private and public ip but in my server is empty is there any thing to be done in php ini file ??
0
private function getIP() { $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if(filter_var($client, FILTER_VALIDATE_IP)) { $ip = $client; } elseif(filter_var($forward, FILTER_VALIDATE_IP)) { $ip = $forward; } else { $ip = $remote; } return $ip; } echo getIP(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.