Problem: One of the big problems after using cloudflare is how to check user IP because PHP default methods are returning Cloudflare IP instead of client IP.
How to Solve it:
While you are using Cloudflare, you can get client IP from Cloudflare request header or using
X-Forwarded-For in client header.
X-Forwarded-For is not a safe method because it can be faked very easy, but if you want an easy way and it’s not important for you to check integrity of IP Address you can use following code:
Easiest method but not safe:
How to check IP from Cloudflare headers?
Cloudflare is using
CF-Connecting-IP header name to send you client final IP Address but if you are allowing users to access your IP or Hosting directly without Cloudflare even this method is not safe!
If you are blocking access outside from cloudflare this an easy safe method:
Safest method: Check REMOTE_ADDR if it’s not from Cloudflare and check
CF-Connecting-IP if it’s from Cloudflare!
You can use REMOTE_ADDR to check integrity of IP Address and get your server request real IP address.
First of All you must check the traffic is coming from Cloudflare or not! it’s not too hard all of Cloudflare IPV4s are available in Cloudflare IP txt. You can check it online or store it in your server but it can change in future.
You can use following code to check both cloudflare and direct client IP:
After importing this functions to your code you just need to call
getRealIp() function like:
$userIp = getRealIp();