Home  >  Article  >  Backend Development  >  How to Get the Real Visitor IP Address When Using CloudFlare in PHP?

How to Get the Real Visitor IP Address When Using CloudFlare in PHP?

DDD
DDDOriginal
2024-10-25 03:40:02675browse

How to Get the Real Visitor IP Address When Using CloudFlare in PHP?

Retrieving Visitor IP Addresses with CloudFlare in PHP

Tracking user activity through IP addresses is a common practice in web development. However, when using CloudFlare for caching and other services, the IP addresses logged via PHP's $_SERVER['REMOTE_ADDR'] may not accurately reflect the true identity of visitors. CloudFlare's IP addresses within the range of 108.162.212. to 108.162.239. mask the actual visitor's IP address.

To address this issue, CloudFlare provides several additional server variables for identifying the connecting IP address of a visitor:

  • $_SERVER["HTTP_CF_CONNECTING_IP"]: This variable contains the visitor's IP address, which allows for accurate IP address logging.
  • $_SERVER["HTTP_CF_IPCOUNTRY"]: It provides the visitor's country.
  • $_SERVER["HTTP_CF_RAY"]: This is a unique identifier for each request.
  • $_SERVER["HTTP_CF_VISITOR"]: It indicates whether the request is made via HTTP or HTTPS.

To retrieve the actual visitor's IP address while using CloudFlare, you can utilize the following code:

<code class="php">if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}</code>

By setting $_SERVER['REMOTE_ADDR'] to the value of $_SERVER["HTTP_CF_CONNECTING_IP"], you can ensure that IP address logs correctly identify the visitors to your website.

Note that the validity of the visiting IP address may still require verification, as anyone could potentially spoof the header information.

The above is the detailed content of How to Get the Real Visitor IP Address When Using CloudFlare in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn