Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
RemoteAddress.php
Go to the documentation of this file.
1 <?php
7 
9 
14 {
20  protected $request;
21 
27  protected $remoteAddress;
28 
33 
37  private $trustedProxies;
38 
44  public function __construct(
45  RequestInterface $httpRequest,
46  array $alternativeHeaders = [],
47  array $trustedProxies = null
48  ) {
49  $this->request = $httpRequest;
50  $this->alternativeHeaders = $alternativeHeaders;
51  $this->trustedProxies = $trustedProxies;
52  }
53 
59  private function readAddress()
60  {
61  $remoteAddress = null;
62  foreach ($this->alternativeHeaders as $var) {
63  if ($this->request->getServer($var, false)) {
64  $remoteAddress = $this->request->getServer($var);
65  break;
66  }
67  }
68 
69  if (!$remoteAddress) {
70  $remoteAddress = $this->request->getServer('REMOTE_ADDR');
71  }
72 
73  return $remoteAddress;
74  }
75 
82  private function filterAddress(string $remoteAddress)
83  {
84  if (strpos($remoteAddress, ',') !== false) {
85  $ipList = explode(',', $remoteAddress);
86  } else {
87  $ipList = [$remoteAddress];
88  }
89  $ipList = array_filter(
90  $ipList,
91  function (string $ip) {
92  return filter_var(trim($ip), FILTER_VALIDATE_IP);
93  }
94  );
95  if ($this->trustedProxies !== null) {
96  $ipList = array_filter(
97  $ipList,
98  function (string $ip) {
99  return !in_array(trim($ip), $this->trustedProxies, true);
100  }
101  );
102  $remoteAddress = trim(array_pop($ipList));
103  } else {
104  $remoteAddress = trim(reset($ipList));
105  }
106 
107  return $remoteAddress ?: null;
108  }
109 
120  public function getRemoteAddress(bool $ipToLong = false)
121  {
122  if ($this->remoteAddress !== null) {
123  return $this->remoteAddress;
124  }
125 
126  $remoteAddress = $this->readAddress();
127  if (!$remoteAddress) {
128  $this->remoteAddress = false;
129 
130  return false;
131  }
132  $remoteAddress = $this->filterAddress($remoteAddress);
133 
134  if (!$remoteAddress) {
135  $this->remoteAddress = false;
136 
137  return false;
138  } else {
139  $this->remoteAddress = $remoteAddress;
140 
141  return $ipToLong ? ip2long($this->remoteAddress) : $this->remoteAddress;
142  }
143  }
144 
150  public function getRemoteHost()
151  {
152  return $this->getRemoteAddress()
153  ? gethostbyaddr($this->getRemoteAddress())
154  : null;
155  }
156 }
__construct(RequestInterface $httpRequest, array $alternativeHeaders=[], array $trustedProxies=null)