CloudFlare and logging visitor IP addresses via in

2019-01-07 03:50发布

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?

8条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-07 04:23

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:

  1. Through Extra Server Headers added by CloudFlare Servers
  2. Adding a CloudFlare Apache/NGINX Module on your server.

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 purpose

In 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

查看更多
神经病院院长
3楼-- · 2019-01-07 04:27

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 .

$ip=$_SERVER["HTTP_CF_CONNECTING_IP"];
if (!isset($ip)) {
  $ip = $_SERVER['REMOTE_ADDR'];
}
查看更多
登录 后发表回答