I'm trying to track and log users/visitors that are accessing my website using PHP's $_SERVER['REMOTE_ADDR']
to do so. A typical method for IP address tracking in PHP.
However, I am using CloudFlare for caching and such and receiving their IP addresses as CloudFlare's:
108.162.212.* - 108.162.239.*
What would be a correct method of retrieving the actual users/visitors IP address while still using CloudFlare?
When you are using CloudFlare all your requests between your server and users are routed through CloudFlare servers.
In this case there are two methods to get User's Real IP Address:
Method 1: Get IP though extra Server Headers
You can use the following code to get user's IP Address:
$user_ip = (isset($_SERVER["HTTP_CF_CONNECTING_IP"]) $_SERVER["HTTP_CF_CONNECTING_IP"]:$_SERVER['REMOTE_ADDR']);
How it is working?
CloudFlare adds some extra server variables in the request as follows:
$_SERVER["HTTP_CF_CONNECTING_IP"]
- Real IP Address of user$_SERVER["HTTP_CF_IPCOUNTRY"]
- ISO2 Country of the User$_SERVER["HTTP_CF_RAY"]
A Special string for loggin purposeIn the above code, we are checking if
$_SERVER["HTTP_CF_CONNECTING_IP"]
is set or not. If it is there we will consider that as user's IP Address else we will use the default code as$_SERVER['REMOTE_ADDR']
Method 2: Installing Cloudflare Module on your server
HTTP_CF_CONNECTING_IP is only working if you are using cloudflare maybe you transfer your site or remove cloudflare you will forget the value so use this code .