PHP

Get Orignal IP while Using Cloudflare DNS in PHP

0
codexjunction

When you’re using Cloudflare’s DNS service and proxying your website through Cloudflare, the original visitor’s IP address is typically hidden, and Cloudflare’s IP addresses are shown in the server logs. However, you can obtain the original IP address of your website visitors in PHP by utilizing the `$_SERVER` superglobal. Cloudflare typically adds the visitor’s IP address to an HTTP header called “CF-Connecting-IP.” Here’s how you can retrieve the original IP address in PHP:

if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$visitor_ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} else {
$visitor_ip = $_SERVER['REMOTE_ADDR'];
}

In this code:

1. We check if the “HTTP_CF_CONNECTING_IP” header is set. If it is, it means the request passed through Cloudflare.

2. If the header is present, we assign its value to the `$visitor_ip` variable, which will contain the original visitor’s IP address.

3. If the “HTTP_CF_CONNECTING_IP” header is not set, we fall back to using `$_SERVER[‘REMOTE_ADDR’]`, which is the default way to retrieve the visitor’s IP address. However, in cases where Cloudflare is in use, it may not contain the original IP address.

By using this method, you can accurately obtain the visitor’s original IP address even when your website is behind Cloudflare’s proxy servers. This is particularly useful for logging or performing IP-based access control while ensuring that your site remains secure.

How to add Custom User Meta values in database WordPress

Previous article

Bootstrap Modal Not Working Properly

Next article

You may also like

Comments

Leave a reply

Your email address will not be published. Required fields are marked *

More in PHP