Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the client's IP address in a PHP webservice? [duplicate]

I have developed a PHP webservice. I would like to log all incoming connections of the WS clients, which are consuming this web service. How can I obtain the client's IP address? The value of

$_SERVER['HTTP_CLIENT_IP']
seems to be always empty.
like image 307
simon Avatar asked Sep 17 '09 09:09

simon


People also ask

How can I get client IP address in PHP?

The simplest way to collect the visitor IP address in PHP is the REMOTE_ADDR. Pass the 'REMOTE_ADDR' in PHP $_SERVER variable. It will return the IP address of the visitor who is currently viewing the webpage.

What is $_ SERVER [' Remote_addr ']?

$_SERVER['REMOTE_ADDR'] Returns the IP address from where the user is viewing the current page. $_SERVER['REMOTE_HOST'] Returns the Host name from where the user is viewing the current page. $_SERVER['REMOTE_PORT']

Which command returns the IP address of the host SERVER PHP?

In order to obtain the IP address of the server one can use ['SERVER_ADDR'], it returns the IP address of the server under the current script is executing. Another method is using the ['REMOTE_ADDR'] in the $_SERVER array.


Video Answer


2 Answers

This should be what you want:

$_SERVER['REMOTE_ADDR'] 

The IP address from which the user is viewing the current page.

http://php.net/manual/en/reserved.variables.server.php

like image 53
Tom Haigh Avatar answered Sep 23 '22 18:09

Tom Haigh


Actually, I would suggest using this function to cover all of your bases, such as people using proxies, shared networks etc.:

function getUserIpAddr() {     if (!empty($_SERVER['HTTP_CLIENT_IP'])) //if from shared     {         return $_SERVER['HTTP_CLIENT_IP'];     }     else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //if from a proxy     {         return $_SERVER['HTTP_X_FORWARDED_FOR'];     }     else     {         return $_SERVER['REMOTE_ADDR'];     } } 
like image 22
bgcode Avatar answered Sep 22 '22 18:09

bgcode