Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复在使用代理服务器时,Request.php无法获取真实客户端IP的功能 #3047

Open
wants to merge 1 commit into
base: 8.0
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/think/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ class Request implements ArrayAccess
* 前端代理服务器真实IP头
* @var array
*/
protected $proxyServerIpHeader = ['HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP', 'HTTP_X_CLIENT_IP', 'HTTP_X_CLUSTER_CLIENT_IP'];
protected $proxyServerIpHeader = [];

/**
* 请求类型
Expand Down Expand Up @@ -1590,6 +1590,32 @@ public function isPjax(bool $pjax = false): bool
return $this->param($this->varPjax) ? true : $result;
}

/**
* 设置代理服务器信息
* @param array $proxyServerIpHeader 代理服务器发来的真实IP的协议头。默认['X-REAL-IP','X-FORWARDED-FOR','CLIENT-IP','X-CLIENT-IP','X-CLUSTER-CLIENT-IP']
* @param array $proxyServerIp 代理服务器IP数组,兼容CIDR格式。用于校验是否是真实的代理服务器,传入0.0.0.0/0表示不校验代理服务器IP
* @return $this
* @throws Exception 传入空数组时将抛出异常,因为你啥都不传你还用调用这个方法干嘛
*/
public function setProxyServer(array $proxyServerIpHeader = [
'X-REAL-IP',
'X-FORWARDED-FOR',
'CLIENT-IP',
'X-CLIENT-IP',
'X-CLUSTER-CLIENT-IP'
], array $proxyServerIp = ['0.0.0.0/0'])
{
if ($proxyServerIp == [] || $proxyServerIpHeader == []) {
throw new Exception('不可传入空数组');
}
foreach ($proxyServerIp as &$value) {
//将$value加上HTTP_前缀,并将-替换为_
$value = 'HTTP_' . str_replace('-', '_', $value);
}
$this->proxyServerIp = $proxyServerIp;
$this->proxyServerIpHeader = $proxyServerIpHeader;
return $this;
}
/**
* 获取客户端IP地址
* @access public
Expand Down