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?
I am rewriting my answer i used for another question "CloudFlare DNS / direct IP identifier"
Cloudflare's ips are stored in public so you can go view them here then check if the ip is from cloudflare (this will allow us to get the real ip from the http header
HTTP_CF_CONNECTING_IP
).If you are using this to disable all non cf connections or vice versa, i recommend you to have a single php script file that gets called before every other script such as a common.php or pagestart.php etc.
To use the script it's quite simple:
This script will show you the real ip address and if the request is CF or not!
Cloudflare sends some additional request headers to your server including
CF-Connecting-IP
which we can store into$user_ip
, if defined, using this simple one-liner:Extra server variables that are available to cloud flare are:
$_SERVER["HTTP_CF_CONNECTING_IP"]
real visitor ip address, this is what you want$_SERVER["HTTP_CF_IPCOUNTRY"]
country of visitor$_SERVER["HTTP_CF_RAY"]
see description here$_SERVER["HTTP_CF_VISITOR"]
this can help you know if its http or httpsyou can use it like this:
If you do this, and the validity of the visiting IP address is important, you might need to verify that the
$_SERVER["REMOTE_ADDR"]
contains an actual valid cloudflare IP address, because anyone can fake the header if he was able to connect directly to the server IP.It would be hard to convert HTTP_CF_CONNECTING_IP to REMOTE_ADDR. So you can use apache (.htaccess) auto prepending to do that. So that you do not need to think about whether the
$_SERVER['REMOTE_ADDR']
has the correct value in all the PHP scripts..htaccess code
php code (file.php)
Learn More here
For magento 1.x users (I haven't try magento 2.0 yet), check https://tall-paul.co.uk/2012/03/13/magento-show-remote-ip-in-cloudflare-the-right-way/ which needs to change app/etc/local.xml and add: HTTP_CF_CONNECTING_IP
Since this question was asked and answered, CloudFlare has released
mod_cloudflare
for Apache, which logs & displays the actual visitor IP address rather than the CloudFlare address:https://www.cloudflare.com/resources-downloads#mod_cloudflare