How can I get the client IP address using PHP?
I want to keep record of the user who logged into my website through his/her IP address.
How can I get the client IP address using PHP?
I want to keep record of the user who logged into my website through his/her IP address.
Here is a cleaner code sample of a good way to get the ip of the user.
Here is a shorter version that uses the elvis operator
Here is a version that uses isset to remove notices (thank you, @shasi kanth)
There are different type of users behind the Internet, So we want to catch the IP address from different potions. That are,
1.
$_SERVER['REMOTE_ADDR']
- This contains the real IP address of the client. That is the most reliable value you can find from the user.2.
$_SERVER['REMOTE_HOST']
- This will fetch the Host name from which the user is viewing the current page. But for this script to work, Hostname Lookups On inside httpd.conf must be configured.3.
$_SERVER['HTTP_CLIENT_IP']
- This will fetch the IP address when user is from Shared Internet services.4.
$_SERVER['HTTP_X_FORWARDED_FOR']
- This will fetch the IP address from the user when he is behind the proxySo we can use this following combined function to get the Real IP address from users who are viewing in diffrent positions,
This is the method that I use, and it validates an IPv4 input:
Like that????
PS
All headers beginning with 'HTTP_' or 'X-' may be spoof respectively is user defined. If you want to keep track use cooies etc.
It should be contained in the
$_SERVER['REMOTE_ADDR']
variable.This function is compact and you can use it everywhere. But !
Don't forget this ! In this type functions or code blocks not guarantee for record the User Real IP because some Users can use proxy or another securely gateways for be invisible or cannot tracking
Php Function :
Usage :
$IP = GetIP();
or directlyGetIP();