How can I get the IP of current user?
How can I get the IP of current user?
You have to decide if you need the IP of the current computer (in the topic name) or of the current user…
If you need the IP address of the user that is visiting your pages then you can use getUserHostAddress() - http://www.yiiframew…tAddress-detail
I want to IP of computer from where the user has logged in or created new account to login. I want to use in login Model.
OK… getUserHostAddress() is what you need…
Example:
<?php echo Yii::app()->request->userHostAddress; ?>
Thank you mdomba.
userHostAddress does not return the actual ip always, depending on the user’s internet provider
something like this would solve it
@Gustavo:
Can you explain, how a user should be able to fake the sender IP address? The $_SERVER[‘REMOTE_ADDR’] (used in getUserHostAddress()) is not related to the ‘Host’ header in the HTTP request. It’s rather the IP address that PHP/Apache obtains from the network stack. I see no way how this numeric value could in any way get altered by the user.
EDIT:
Fixed typo, it’s REMOTE_ADDR, not REMOTE_HOST
The user cannot alter it… but if someone uses a PROXY… then you can get the proxy ip or to be clear wan ip…
Some proxy’s (not so effective ones) in turn set another variable to the original users wan ip… but if a proxy is good then you cannot get in any way the original user wan ip…
On top of that there are many variants that could be set by a proxy server like:
$_SERVER["HTTP_VIA"]
$_SERVER["CLIENT_IP"]
$_SERVER["HTTP_CLIENT_IP"]
$_SERVER["HTTP_FROM"]
$_SERVER["HTTP_FORWARDED"]
$_SERVER["HTTP_X_FORWARDED"]
$_SERVER["HTTP_X_FORWARDED_FOR"]
$_SERVER["HTTP_PROXY_REMOTE_ADDR"]
$_SERVER["HTTP_PROXY_CONNECTION"]
$_SERVER["HTTP_REMOTE_IP"]
$_SERVER["HTTP_SCANNER_HOST"]
perfect answer from mdomba, nothing to add
Ps.: in the code I wrote in the link posted only checks for the most commom proxys, like aol and a couple others
I’m using Yii::app()->request->userHostAddress but keep getting localhost (127.0.0.1) for every single user.
Any ideas why?
The IP address belongs to the computer you are connecting from… not to a user… so if you have the web server on the same computer you are working your IP address is "localhost" = "127.0.0.1" …
ignition25:
If you talk about a public server, do you maybe have a reverse proxy in front of your Apache (like nginx)?
Yep, I have nginx sitting in front of Apache
nginx will then create a new request to Apache. By default these requests will originate from localhost (because that’s where nginx is). You can try this setting in nginx config:
proxy_set_header REMOTE_ADDR $remote_addr;
Ah yes, of course. Thanks for the heads up.
Decided to use the Apache Request Header: "X-Forwarded-For" to grab this info.