How can we able to get the client IP address using PHP?
- We want to keep record of the user who logged into our website through IP address.
- The simplest way is remote address server super global. But this is not the best way to do is using different server super global functions, http client IP and http x forwarded for, remote address.
- By using these three functions we can get correct ip address of a client or computer who is accessing our website.
- Simply use the below code to get client IP address in php.
we can use different server super global functions to check valid IP address.(http client IP and http x forwarded for, remote address)
Note: Using the above code has security implications. The client can set all HTTP header information (ie. $_SERVER[‘HTTP_…) to any arbitrary value it wants. As such it’s far more reliable to use $_SERVER[‘REMOTE_ADDR’], as this cannot be set by the user.
Try this :
Here is a shorter version that uses the elvis operator
- This is the method validates an IPv4 input:
- Another method of implementation:
There are different type of users behind the Internet, So we want to catch the IP address from different potions. They are,
1. $_SERVER[‘REMOTE_ADDR’] – It contains the real IP address of the client. This is the most reliable value we can able to find from the user.
2. $_SERVER[‘REMOTE_HOST’] – It 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’] – It will fetch the IP address when user is from Shared Internet services.
4. $_SERVER[‘HTTP_X_FORWARDED_FOR’] – It will fetch the IP address from the user when he is behind the proxy
using the GLOBAL variable named as $_SERVER.
the $_SERVER is an array which has an attribute names REMOTE_ADDR.
Just assign it like this $userIp = $_SERVER[‘REMOTE_ADDR’];
or use it directly like echo $_SERVER[‘REMOTE_ADDR’]; or echo ($_SERVER[‘REMOTE_ADDR’]);
- We can able to use $_SERVER[‘REMOTE_ADDR’]; to get client IP address and if we need more information about a user, Use below sample code:
- Client’s more specific info goes in $clientDetails.We can able to fetch json items stored in $clientDetails variable in this way: $clientDetails->PostalCode/hostname/region/loc..
- Here is the another solution to get the ip address