2020年10月20日 星期二

使用CloudFlare,來源IP會改變,這裡是用法

CloudFlare 會額外增加SERVER Variable變數,如下: 

$_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"]

$_SERVER["HTTP_CF_VISITOR"] this can help you know if its http or https


you can use it like this:

if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {

  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];

}

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.


參考網址:

https://stackoverflow.com/questions/14985518/cloudflare-and-logging-visitor-ip-addresses-via-in-php

https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs-Logging-visitor-IP-addresses

https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-Cloudflare-handle-HTTP-Request-headers-


但是我使用$_SERVER["HTTP_CF_CONNECTING_IP"] 發現得出來的 IP是:2001:b011:3009:17b8:8871:298c:88d7:9104,不是IPV4格式

這還要研究一下。

我現在暫時修改了 common.php 裡面的

if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {

  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];

}

if (CCGetUserAddr() != $_SERVER["REMOTE_ADDR"]) { CCLogoutUser(); }




--------------------

另外:

PHP 取得用戶真實 IP

https://devco.re/blog/2014/06/19/client-ip-detection/
https://ithelp.ithome.com.tw/articles/10216399



<?php
if (!empty($_SERVER["HTTP_CLIENT_IP"])){
    $ip = $_SERVER["HTTP_CLIENT_IP"];
}elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}else{
    $ip = $_SERVER["REMOTE_ADDR"];
}
    
echo $ip;
?>


可以參考的 HTTP Header(依照可能存放真實 IP 的順序)

  • HTTP_CLIENT_IP
  • HTTP_X_FORWARDED_FOR
  • HTTP_X_FORWARDED
  • HTTP_X_CLUSTER_CLIENT_IP
  • HTTP_FORWARDED_FOR
  • HTTP_FORWARDED
  • REMOTE_ADDR (真實 IP 或是 Proxy IP)
  • HTTP_VIA (參考經過的 Proxy)




沒有留言:

張貼留言

如何判斷現在FORM是在 insert mode? 還是 update mode?

只要用  if (empty({primary_key})) 就可以知道是否為新增模式了。 如果 {promary_key} 是空白的,那麼就是在新增模式;反之,就是更新模式。 以上。